Author Topic: Question of optionals Exercise 5.1  (Read 3626 times)

mmuldoon

  • Newbie
  • *
  • Posts: 2
    • View Profile
Question of optionals Exercise 5.1
« on: September 16, 2015, 07:55:41 AM »
On the line that you set self.lblDemo.text = self.lblDemo.text.stringByReplacingString........

I notice after entering the arugments and completing the method call, XCode adds a question mark after self.lblDemo.text?stringBy....

Why is it and optional and why don't we have to unwrap it?

Thanks!!

~M

angelina

  • Global Moderator
  • *****
  • Posts: 25
    • View Profile
Re: Question of optionals Exercise 5.1
« Reply #1 on: July 08, 2016, 06:33:07 PM »
The text property of lblDemo is an optional because the value may be nil.  In other words, the lblDemo label may or may not have it’s text property set, which would result in a value of nil for the text property.  The Xcode error message says, “Value of optional type ‘String?’ not unwrapped; did you mean to use ‘!’ or ‘?’ ?.   

By using the ‘!’ or the ‘?’, you are essentially unwrapping it.  When you use the “?” after “text” you are using optional chaining and the method stringByReplacingOccurencesOfString will only be called if the text value is not nil. When you use the ‘!’,  you are using forced unwrapping to unwrap it so the method will be called regardless.  In this case, if the text value is nil, you will get a compile time error.  On page 58, it says, “The moral of the story is: don’t use forced unwrapping unless you are absolutely sure the optional value is not nil!”  So, in this case, since we previously gave the lblDemo text property a value, we know it’s not going to be nil, so we can use the ‘!’ to force unwrap it.


Angelina
Oak Leaf Enterprises, Inc.