Search code examples
swiftoptional-values

Difference between optional values in swift?


What is the difference between:

var title:String? = "Title" //1
var title:String! = "Title" //2
var title:String = "Title" //3

What am I saying if I were to set title in each way and am I forced to unwrap each variable in a different way?


Solution

  • Think about ? and ! like a box that might have a value or not. enter image description here

    I recommend this article.

    1. Optional box that might have value or might not, and that optional box is not unwrapped.

      var title:String? = "Title" //second and third picture
      

      You use unwrapped value like that:

      if let title = title {
          //do sth with title, here is the same like let title: String = "Title"
      }
      
    2. Optional box that might have a value or might not, and that optional box is actually unwrapped. If there is a value and you access that value, that is ok (second image, just replace ? with !), but if there is no value, then app crash (third image, just replace ? with !)

      var title:String! = "Title"
      
    3. That variable have a value for sure, and you cannot assign to this value nil (because it is not optional). Optional means that there is a value or there is no value (nil):

      var title:String = "Title" //first picture