有没有办法在Swift中延迟返回语句?

我想知道是否有任何方法可以延迟函数的返回语句......例如:

func returnlate() -> String {
    var thisStringshouldbereturned = "Wrong"
    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
        // Here should be the String changed
        thisStringshouldbereturned = "right"
    }
    // The Return-Statement returns the First Value ("Wrong")
    // Is there a way to delay the return Statement?
    // Because you can't use 'DispatchQueue.main.asyncAfter(deadline: .now() + 1)'
    return thisStringshouldbereturned
}

谢谢,祝你有美好的一天,保持健康。

布索什

回答

您正在寻找一个closure,又名完成处理程序。

return立即执行,没有办法延迟。相反,您可以使用完成处理程序,它通过将闭包作为参数传递来工作。然后可以在延迟后调用此关闭。

                            /// closure here!
func returnLate(completion: @escaping ((String) -> Void)) {
    var string = "Wrong"
    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
        string = "right"
        completion(string) /// similar to `return string`
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    returnLate { string in
        print("String is (string)") /// String is right
    }
}


以上是有没有办法在Swift中延迟返回语句?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>