iOS/Swift: Can't assign optional String to UILabel text property

11,911

You don't need to unwrap text.

Leaving text as an String? (aka Optional<String>)

cell.tweetContent.text = unopt // Works: String implicitly wraps to Optional<String>
cell.tweetContent.text = opt   // Works: Optional<String>

Where as unwrapping text turns String? into a String.

cell.tweetContent.text? = unopt // Works: String
cell.tweetContent.text? = opt   // Fails: Optional<String> cannot become String

UPDATE

Maybe there needs to be a bit more of an explanation here. text? is worse than I originally thought and should not be used.

Think of text = value and text? = value as function setText.

text = has the signature func setText(value: String?). Remember, String? is Optional<String>. In addition, it's always called no matter the current value of text.

text? = has the signature func setText(value: String). Here is the catch, it's only called when text has a value.

cell.tweetContent.text = nil
cell.tweetContent.text? = "This value is not set"
assert(cell.tweetContent == nil)
Share:
11,911
DenverCoder9
Author by

DenverCoder9

Dear people from the future: Here's what we've figured out so far...

Updated on June 04, 2022

Comments

  • DenverCoder9
    DenverCoder9 almost 2 years

    UILabel has a text property, which is an optional String, but it seems to be behaving like an implicitly unwrapped optional. Why can't I assign it another optional String? Thanks.

    @IBOutlet weak var tweetContent: UILabel!
    

    ...

    var unopt: String = "foo"
    var opt: String? = "bar"
    var opt2: String?
    opt2 = opt                       //Works fine
    cell.tweetContent.text? = unopt  //Works fine
    cell.tweetContent.text? = opt    //Compile error: Value of optional type 'String?' not unwrapped
    
  • DenverCoder9
    DenverCoder9 about 9 years
    Thanks. I want to learn more about this, is there a specific name for adding the question mark to the left operand of an assignment?