Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 776
jshah Avatar asked Oct 29 '25 14:10

jshah


1 Answers

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
    
like image 109
Bartłomiej Semańczyk Avatar answered Oct 31 '25 04:10

Bartłomiej Semańczyk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!