When I am getting a value back from an API that I am hitting, when I print the data it appears as
Optional((
jknjknjkn
))
for example. I use a selector to run a method when the data is returned
func result(data: AnyObject){
println(data["info"])
}
What is printed is the Optional thing above. How can I get the value without that Optional() thing wrapping it?
Here is the raw data if I just print data
<AppUser: 0x78ec5650, objectId: I6nxFSZx9h, localId: (null)> {
AppID = (
jknkjnjknkn
);
info = (
jknjknjkn
);
}
In Swift, an optional is a variable that can either hold a value or nil (no value at all). To get the value from it, you have to unwrap it with an exclamation point:
func result(data: AnyObject){
println(data["info"]!)
}
Note that if data["info"] was nil, your app would crash with this error message:
fatal error: unexpectedly found nil while unwrapping Optional value
If you are concerned that the expression might produce nil, you can use optional binding:
func result(data: AnyObject){
if let info = data["info"] { //info is now the unwrapped version of `data["info"]
println(info) //will only be executed if data["info"] is not nil
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With