swift async_v1.swift

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift async_v1.swift相关的知识,希望对你有一定的参考价值。


import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

func async<T>(_ executable: @escaping @autoclosure () -> T, _ priority: DispatchQoS.QoSClass = DispatchQoS.QoSClass.default, completion: @escaping (T) -> Void) {
    DispatchQueue.global(qos: priority).async {
        let result = executable()
        DispatchQueue.main.async {
            completion(result)
        }
    }
}

func asyncWithError<T>(_ executable: @escaping @autoclosure () throws -> T, _ priority: DispatchQoS.QoSClass = DispatchQoS.QoSClass.default, completion: @escaping (T?, Error?) -> Void) {
    DispatchQueue.global(qos: priority).async {
        var result: T? = nil
        var error: Error? = nil
        do {
            result = try executable()
        }
        catch let caughtError {
            error = caughtError
        }
        DispatchQueue.main.async {
            completion(result, error)
        }
    }
}

class TestExecutor {
    
    func perform(_ input: String) -> String {
        return input + " Performed"
    }
    
    enum Error: String, Swift.Error, LocalizedError {
        case Empty
        
        var errorDescription: String? {
            return self.rawValue
        }
    }
    
    func throwingPerform(_ input: String) throws -> String {
        if input.isEmpty {
            throw Error.Empty
        }
        
        return self.perform(input)
    }
    
}

let executor = TestExecutor()

let syncResult = executor.perform("Hi")

async(executor.perform("Async")) { result in
    print(result)
}

asyncWithError(try executor.throwingPerform("")) { result, error in
    print("result: ", result ?? "no result", ", error: ", error?.localizedDescription ?? "no error")
    PlaygroundPage.current.finishExecution()
}

以上是关于swift async_v1.swift的主要内容,如果未能解决你的问题,请参考以下文章

swift 指定的初始值设定,1.swift

swift AuthDelegateViewController-1.swift

swift SPLITVIEW-example1.swift

Swift 3.0 on Ubuntu 15.10

1.Swift教程翻译系列——关于Swift

swift学习网址