var a:Int?a? = 10print(a)
这里变量a没有被分配值10.如果是因为’?’运算符,为什么编译器不显示编译错误?
@R_301_6120@ 试试这个var a:Int?a = 10print(a)
好…
? (Optional) indicates your variable may contain a nil value while ! (unwrapper) indicates your variable must have a memory (or value) when it is used (trIEd to get a value from it) at runtime.
主要区别在于,当optional是nil时,可选链接会正常失败,而当optional可选为nil时,强制解包会触发运行时错误.
var defaultNil : Int? // declared variable with default nil valueprintln(defaultNil) >> nil var canBeNil : Int? = 4println(canBeNil) >> optional(4)canBeNil = nilprintln(canBeNil) >> nilprintln(canBeNil!) >> // Here nil optional variable is being unwrapped using ! mark (symbol),that will show runtime error. Because a nil optional is being trIEd to get value using unwrappervar canNotBeNil : Int! = 4print(canNotBeNil) >> 4var cantBeNil : Int = 4cantBeNil = nil // can't do this as it's not optional and show a compile time error
Here is basic tutorial in detail,by Apple Developer Committee.
总结以上是内存溢出为你收集整理的使用?分配给swift 3.0中的可选变量?运算符返回nil全部内容,希望文章能够帮你解决使用?分配给swift 3.0中的可选变量?运算符返回nil所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)