1、可选型与元组使用
var error1:(errorCode: Int, errorMessage: String?) = ( 404 , "Not Found")
error1.errorMessage = nil
//error1 = nil //错误的
//此时error1.errorMessage是可选型,error1不为可选型
var error2:(errorCode: Int, errorMessage: String)? = ( 404 , "Not Found")
error2 = nil
//error2.errorMessage = nil //错误的
//此时error2.errorMessage不为可选型,error2为可选型
var error3:(errorCode: Int, errorMessage: String?)? = ( 404 , "Not Found")
error3 = nil
error3.errorMessage = nil
//此时error3.errorMessage和error3都为可选型
2、可选型的实际应用
// Int()返回的值为可选型
var ageInput1: String = "16"
var ageInput2: String = "zxc"
let age1 = Int(ageInput1) //16
let age2 = Int(ageInput2) //nil
let age = Int(ageInput1) //16
if let age = age , age < 20{
print("You're a teenager!")
}
// Optional in String method
var greetings = "Hello"
greetings.range(of: "ll") //返回rang
greetings.range(of: "oo") //返回nil
//range(of: "ll")方法返回值为可选型