Swift:如何从completionHandler中获得价值
func getMac(_ session: String, _ kitcode: String) -> String { var mac: String = "" api.get_kit(session,kitcode) { resDevice in var m: String = "" for obj in resDevice { if obj.type == 1 { m = obj.mac break } } print("M : " + m) mac = m } return mac }
我需要var m
返回func
请帮帮我。
我想多解释一下,但是我不擅长语言。
你有两个select
1)通过closures作为你的函数参数
func getMac(_ session: String, _ kitcode: String, completion: @escaping (String) -> Void) { api.get_kit(session,kitcode) { resDevice in var mac: String = "" for obj in resDevice { if obj.type == 1 { mac = obj.mac break } } print("M : " + mac) completion(mac) } }
用法:
getMac("session", "kitcode") { mac in print(mac) }
2)同步
2.1)一般
let semaphore = DispatchSemaphore(value: 0) var text = "Some text" DispatchQueue.global(qos: .default).async { sleep(5) text = "Some other text" semaphore.signal() } print(text) // "Some text\n" _ = semaphore.wait(timeout: DispatchTime.distantFuture) print(text) // "Some other text\n"
2.2)Alamofire
let semaphore = DispatchSemaphore(value: 0) let request = Alamofire.request("https://someAlamofireRequest.url/") var text = "Some text" request.response(queue: DispatchQueue.global(qos: .default)) { _ in text = "Some other text" semaphore.signal() } print(text) // "Some text\n" _ = semaphore.wait(timeout: DispatchTime.distantFuture) print(text) // "Some other text\n"
你必须使用块来获得价值
func getMac(_ session: String, _ kitcode: String, successHandler: @escaping (_ success:String) -> Void) { var mac: String = "" api.get_kit(session,kitcode) { resDevice in var m: String = "" for obj in resDevice { if obj.type == 1 { m = obj.mac break } } print("M : " + m) mac = m successHandler(mac) } }
func getMac(_ session: String, _ kitcode: String, completion:(_ value: String) -> Void) { api.get_kit(session,kitcode) { resDevice in var mac: String = "" for obj in resDevice { if obj.type == 1 { mac = obj.mac break } } print("M : " + mac) completion(mac) }
用作这个function
getMac("yourstring", "yourstring", completion: { (value) -> () in print(value) })