swift - Can't change a variable inside an if let -
i have small function "should" change uilabel's text, i'm getting hung on how unwrapped value if let statement.
func update() { var straddress = "test" ip.getipaddress { (data) -> void in let json = json(data: data) if let address = json["ip"].string { println("address: \(address)") straddress = (address) } else { println("not unwrapped") } } self.lblipaddress.text = straddress }
the result of json["ip"] working, assume println shows "address: xxx.xxx.xxx.xxx". trouble isn't that, it's trying assign constant "address" variable straddress.
i've tried statically set straddress "test" inside if let, still won't change.
any ideas?
your ip.getipaddress seems call closure asynchronously meaning executed after in queue done.
so in function reaches self.lblipaddress.text = straddress
before...
{ (data) -> void in let json = json(data: data) if let address = json["ip"].string { println("address: \(address)") straddress = (address) } else { println("not unwrapped") } }
...is executed.
for work want have put self.lblipaddress.text = straddress
inside closure.
ip.getipaddress { (data) -> void in let json = json(data: data) if let address = json["ip"].string { println("address: \(address)") straddress = (address) } else { println("not unwrapped") } dispatch_async(dispatch_get_main_queue()) { // make sure called on main thread self.lblipaddress.text = straddress } }
Comments
Post a Comment