【问题标题】:Is there a way to delay a return-Statement in Swift?有没有办法在 Swift 中延迟返回语句?
【发布时间】:2021-04-29 19:36:25
【问题描述】:

想知道有没有什么办法可以延迟函数的return语句……举个例子:

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
}

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

展位

【问题讨论】:

    标签: swift


    【解决方案1】:

    您正在寻找 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
        }
    }
    

    【讨论】:

    • 好的,感谢您的快速回答,我会试试看!
    猜你喜欢
    • 2019-03-15
    • 2016-02-17
    • 1970-01-01
    • 2016-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    • 2012-12-30
    相关资源
    最近更新 更多