SWIFT中有一个类型定义叫可选值,在变量类型后面加一个?号即可定义一个类型为Optional Value的变量,当在使用变量时要用到强制解包!.
如在页面上有一个可选输入年龄的框,在接受数据的时间就可能要定义一个可选值的变量.
var age:Int? = 10
var str:String = "Age is "+String(age!)
以下为从一个数组中取数据,然后判断是否存在值
var numberOfLegs = ["ant":6, "snake":0, "dog":4]
var possibleLegCount:Int? = numberOfLegs["fish"] //没有找到相应的键值将会返回nil
判断possibleLegCount是否是nil
if possibleLegCount == nil{
println("not found")
}else{
var legCount = possibleLegCount! //强制解包
println("fish's legs is (legCount)")
println("fish's legs is (possibleLegCount)") //用这种占位方式会自动解包
}
此时的possibleLegCount一定要是Optional Value类型,否则会报错.此时程序将会验证可选值是否可以正常解包,正常的话将会把值解包后赋值给legCount变量
if let legCount = possibleLegCount {
println("fish's legs is (legCount)")
}
另外SWIFT中的可能值类型其实是一个Enumeration,如下代码将会打印"My name is Ken",如果将myName的值去掉将会打印"I don't have name"
var myName:String? = "Ken"
switch myName{
case .Some(let name):
println("My name is (name)")
case nil:
println("I don't have name ")
default:
println("default")
}