Can't unwrap 'Optional.None'

后端 未结 3 1850
北海茫月
北海茫月 2020-12-10 16:19

When confronting the error fatal error:

Can\'t unwrap Optional.None

It is not that easy to trace this. What causes this error?

<
3条回答
  •  既然无缘
    2020-12-10 16:43

    You get this error, because you try to access a optional variable, which has no value. Example:

    // This String is an optional, which is created as nil.
    var optional: String?
    
    var myString = optional! // Error. Optional.None
    
    optional = "Value"
    if optional {
        var myString = optional! // Safe to unwrap.
    }
    

    You can read more about optionals in the official Swift language guide.

提交回复
热议问题