Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do blocks guarantee local variables will be modified in Swift?

Tags:

ios

swift

cocoa

func foo() -> Bool {
    var apiResult : Bool = false
    myAPI.bar() { (result: Bool) -> Void in
        // some logic in block and local variable assignment
        apiResult = result
    }
    return apiResult
}

Is the value of apiResult guaranteed to be updated by the block passed in? (I am a college student learning iOS, so please be as informative as possible)

like image 200
Madhav Sharma Avatar asked Dec 14 '25 15:12

Madhav Sharma


1 Answers

You are passing the closure (block) to the myAPI.bar function. The function may or may not call the closure. If the closure is called then apiResult would change. The change may occur after the function foo returns though, depending on how myAPI.bar is implemented.

like image 123
Code Avatar answered Dec 17 '25 08:12

Code



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!