3

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

rmaddy
  • 314,917
  • 42
  • 532
  • 579
iOSGuy
  • 171
  • 1
  • 14
  • you should study the Opitinal :http://stackoverflow.com/questions/24003642/what-is-an-optional-value-in-swift – aircraft Feb 03 '17 at 05:04
  • Yeah! @aircraft gives you right link, first read it out.`Optional` word is not the part of the string . `Optional` just tells you that this `param` can be `nil` but its current value is `hello` . – dahiya_boy Feb 03 '17 at 05:11

2 Answers2

6

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
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • so all the times I've see optional values for textField/textView/UILabel, they were all during my debugging?! And none were for when I was looking at the actual screen? Hard to believe :D – mfaani Nov 05 '18 at 20:32
0

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!

mfaani
  • 33,269
  • 19
  • 164
  • 293