Why can you assign non-optional values to optional types in Swift?

后端 未结 2 1370
孤城傲影
孤城傲影 2021-01-06 19:40

Why do assignments involving Swift optionals type check? For example in,

 var foo : Int? = 0
 foo = foo!

foo and foo! do not have the same

2条回答
  •  一生所求
    2021-01-06 20:13

    After reading rickster's answer, I came up with a simple laymen terms answer. To me the whole whole gist of his answer is

    Since an optional indicates the presence or absence of a value, you shouldn't have to do anything special to indicate the presence of a value other than provide one

    An optional is an enum. Which has 2 cases a or b.

                                          String?
                                             |
                                    An enum with 2 cases
                                             |                               
                                     a               b
                                     |               |
                                    Set            notSet
                                     |               |
                            any value like "hi"     nil
    

    So you could do either of the things when you want to assign to an optional.

    Say the value is either:

    • a: it's set to "hi"
    • b: it's not set, so it's nil
    • c: it just equals to another enum ie another optional

    code:

    var str : String?
    var anotherOptional : String?
    
    str = nil // nil <-- this is like case b
    str = "hi" // "hi" <-- this is like case a
    
    str = anotherOptional // nil <-- this is like case c
    
    anotherOptional = "hi again"
    str = anotherOptional // "hi again" <-- this is like case c
    

提交回复
热议问题