What does an exclamation mark mean in the Swift language?

后端 未结 22 2680
南方客
南方客 2020-11-22 03:47

The Swift Programming Language guide has the following example:

class Person {
    let name: String
    init(name: String) { self.name = name }
    var apar         


        
22条回答
  •  情书的邮戳
    2020-11-22 04:19

    An Optional variable may contain a value or may be not

    case 1: var myVar:String? = "Something"

    case 2: var myVar:String? = nil

    now if you ask myVar!, you are telling compiler to return a value in case 1 it will return "Something"

    in case 2 it will crash.

    Meaning ! mark will force compiler to return a value, even if its not there. thats why the name Force Unwrapping.

提交回复
热议问题