Bhavin_m
Bhavin_m

Reputation: 2784

How to use string variable without unwrap optional value

I am very confused with unwrap fundamentals of Swift 2.0. I have bellow code to display last name string value from dictionary to label.

let lastName:String? = self.userDict.objectForKey("last_name")
self.lblLastName.text = "Last Name: " + lastName!

but some times this code run before value assign in to self.userDict at that time above code get self.userDict.objectForKey("last_name") nil and throw an error.

For solution i modified my code like bellow and keep that value unwrap but compiler don't take it as valid

let lastName:String? = self.userDict.objectForKey("last_name")
self.lblLastName.text = "Last Name: " + lastName?   //--ERROR: Value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?

Please suggest me valid way to fulfil the requirement.

Upvotes: 1

Views: 660

Answers (2)

Rashmi Ranjan mallick
Rashmi Ranjan mallick

Reputation: 6620

You could also use Optional Binding to check if the retrieved value from dictionary is nil or not. Then you can assign the string to your label (lblLastName) conditionally.

if let lastName = self.userDict.objectForKey("last_name") {
    self.lblLastName.text = "Last Name: " + lastName
} else {
    self.lblLastName.text = "Last Name: " + "some other hard coded string"
}

Upvotes: 1

0x416e746f6e
0x416e746f6e

Reputation: 10126

You need to provide a way to handle cases when dictionary has no value for key "last_name" and returns nil. Easiest way is to use nil coalescing operator ??:

The nil coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type. The expression b must match the type that is stored inside a.

You could do something like:

let lastName: String = self.userDict.objectForKey("last_name") ?? "N/A"
self.lblLastName.text = "Last Name: " + lastName

Upvotes: 6

Related Questions