1

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.

4
  • You should use ! instead of ? to force unwrap optional Commented Oct 30, 2015 at 7:00
  • developer.apple.com/library/ios/documentation/Swift/Conceptual/… Commented Oct 30, 2015 at 7:02
  • 3
    @ozzyzig No. That's a very bad advice. Force unwrapping leads to crashes on user side. Instead, always use safe techniques like optional binding, optional chaining, etc. Commented Oct 30, 2015 at 9:17
  • 1
    Sorry I forgot to say test with an if let statement. Commented Oct 30, 2015 at 18:43

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

2 Comments

Solved +1 :) thanks for help. But please can you give little exploitation on ?? operator. I am totally unaware of this.
Yes, I was busy with exactly that. Please see the edits to the answer.
1

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"
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.