iOSGuy
iOSGuy

Reputation: 181

UIlabel text does not show "optional" word when setting optional text?

I have been using optional a lot.I have declared a string variable as optional

var str: String?

Now i set some value in this variable as str = "hello".Now if i print this optional without unwrapping then it print as

Optional("hello")

But if i set text on the label as self.label.text = str then it just display value as

hello

Please explain why it does not show text as on label

Optional("hello")

Upvotes: 3

Views: 1591

Answers (2)

mfaani
mfaani

Reputation: 36427

I knew I've seen optionals printed in UILabel, UITextView, UITextField. Rmaddy's answer wasn't convincing.

It's very likely that there is an internal if let else so if the optional has a value then it will unwrap it and show. If not then it would show nothing.

However there's a catch!

let optionalString : String? = "Hello World"

label.text = "\(optionalString)" // Optional("Hello World")
label.text = optionalString // Hello World

let nilOptionalString : String?

label.text = "\(nilOptionalString)" // `nil` would be shown on the screen. 
label.text = nilOptionalString // no text or anything would be shown on the screen . It would be an empty label.

The reason is that once you do "\(optionalVariable)" then it would go through a string interpolation and once its a String and not String? then the result of the interpolation would be shown!

Upvotes: 0

rmaddy
rmaddy

Reputation: 318914

The text property of UILabel is optional. UILabel is smart enough to check if the text property's value is set to nil or a non-nil value. If it's not nil, then it shows the properly unwrapped (and now non-optional) value.

Internally, I imagine the drawRect method of UILabel has code along the lines of the following:

if let str = self.text {
    // render the non-optional string value in "str"
} else {
    // show an empty label
}

Upvotes: 6

Related Questions