swift语言-可选类型

前端之家收集整理的这篇文章主要介绍了swift语言-可选类型前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

可选类型

什么是可选类型

可选值类型的数据有两种可能:有值、没有值(nil)。注意需要在变量类型后面加问号(?)。如果是Int加问号(?),则变量的为Int?型的。问号(?)是可选类型的标志。
可选值可以使用if判断有没有值

@H_403_8@#import Foundation var optValue: Int? = nil if optValue != nil{ println("not nil") }else{ println("nil") }

如何获得可选值里的值?

强制解析
注意在可选变量后加感叹号(!)
感叹号是强制解析的标志。

@H_403_8@#import Foundation //非nil情况 var optValue:Int? = 3 println(intValue) //会打印Optional(3) println(intValue!) //会打印3 var intValue:Int = optValue! println(intValue) //可选类型的Int才能赋值为nil,普通的Int只能赋值整型 var optValue1:Int? = nil //var intValue2:Int = optValue1! //println(intValue2)

注意如果强制解析没有值可能会一起运行时错误。所以最好加个是否为nil的判断。

@H_403_8@#import Foundation var optValue1:Int? = nil if optValue1 != nil { println(optValue1!) }

可选绑定
增加一个临时量并给临时变量赋可选值,通过if条件判断获得可选类型的值
如果可选类型的变量没有值if条件不满足,如果可选类型变量有值则通过临时变量获得值

@H_403_8@#import Foundation var optValue1:Int? = nil if let tempValue = optValue1 { println(tempValue) }

猜你在找的Swift相关文章