swift可选类型 和隐式可选类型

标识符:?和!
声明格式:

var str:String? ->可选类型 可以=nil
var str:String! ->隐式可选类型 可以=nil
var str:String = "stirng" ->非可选类型 不可以=nil

例1:

var str = "Hello, playground"
str = nil //编译报错:Nil cannot be assigned to type 'String'

var str: String = "Hello, playground"
str = nil //Nil cannot be assigned to type 'String'

例2:

var str: String! = "Hello, playground"
str = nil  //编译通过 str == nil
print(str) //不必使用!

例3:

var str: String? = "Hello, playground"
print(str ?? " nil ")
print(str!)

你可能感兴趣的:(swift可选类型 和隐式可选类型)