Can't unwrap 'Optional.None'

后端 未结 3 1836
北海茫月
北海茫月 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:34

    When you see this error this is due to an object such as an unlinked IBOutlet being accessed. The reason it says unwrap is because when accessing an optional object most objects are wrapped in such a way to allow the value of nil and when accessing an optional object you are "unwrapping" the object to access its value an this error denotes there was no value assigned to the variable.

    For example in this code

    var str:String? = nil
    var empty = str!.isEmpty
    

    The str variable is declared and the ? denotes that it can be null hence making it an OPTIONAL variable and as you can see it is set to nil. Then it creates a inferred boolean variable empty and sets it to str!.isEmpty which the ! denotes unwrap and since the value is nil you will see the

    Can't unwrap Optional.None error
    

提交回复
热议问题