Reputation: 2784
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
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
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 optionala
if it contains a value, or returns a default valueb
ifa
isnil
. The expressiona
is always of an optional type. The expressionb
must match the type that is stored insidea
.
You could do something like:
let lastName: String = self.userDict.objectForKey("last_name") ?? "N/A"
self.lblLastName.text = "Last Name: " + lastName
Upvotes: 6