Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift getting value inside Optional() [closed]

Tags:

xcode

ios

swift

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
);
}
like image 328
Jason Storey Avatar asked Aug 06 '26 13:08

Jason Storey


1 Answers

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
    }
}
like image 124
NobodyNada Avatar answered Aug 09 '26 02:08

NobodyNada