Is there a way to delay a return-Statement in Swift?

Viewed 508

I wondered if there is any way to delay the return statement of an function... an example:

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
}

Thanks, have a nice day and stay healthy.

Boothosh

1 Answers

You are looking for a closure, a.k.a. completion handler.

return executes immediately and there is no way to delay that. Instead, you can use completion handlers, which work by passing in a closure as a parameter. This closure can then be called after a delay.

                            /// 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
    }
}
Related