How do you unwrap Swift optionals?

前端 未结 5 1188
难免孤独
难免孤独 2020-11-27 04:14

How do you properly unwrap both normal and implicit optionals?

There seems to be confusion in this topic and I would just like to have a reference for all of the way

5条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 05:00

    An optional type means that the variable might be nil.

    Example:

    var myString: Int? = 55
    myString = nil
    

    The question mark indicates it might have nil value.

    But if you state like this:

    var myString : Int = 55
    myString = nil
    

    It will show error.

    Now to retrieve the value you need to unwrap it:

    print(myString!)
    

    But if you want to unwrap automatically:

    var myString: Int! = 55
    

    Then:

    print(myString)
    

    No need to unwrap. Hope it will help.

提交回复
热议问题