可选型

var errorCode: Int? = 90
errorCode = 0
errorCode = nil//只有是可选类型,才可以赋值nil
var color: UIColor? = nil

//可选型的解包Umwrap---在可选型的后面加!,强制解包有风险
var errorStr:String? = "404"
print(errorStr)
"The errorStr is " + errorStr!

if errorStr != nil {
    "The errorStr is " + errorStr!
}else{
    "No error"
}
//if let 解包
if let upwrapErrorStr = errorStr {
    "The errorStr is " + upwrapErrorStr
}else{
    "No error"
}
var errorMessage:String? = "NOt found"
if let errorStr = errorStr{
    if let errorMessage = errorMessage{
        "The errorStr is " + errorStr + "\nThe errorMessage is " + errorMessage
    }
}

if let errorStr = errorStr,
    errorMessage = errorMessage{
    "The errorStr is " + errorStr + "\nThe errorMessage is " + errorMessage
}
//既解包,又做了逻辑判断
if let errorStr = errorStr,
    errorMessage = errorMessage where errorStr == "404" {
        "The errorStr is " + errorStr + "\nThe errorMessage is " + errorMessage
}

var errorMessage:String? = "Not found"
if let errorMessage = errorMessage{
    errorMessage.uppercaseString
}
//等价于
errorMessage?.uppercaseString//安全的,当errorMessage=nil时,返回的是nil
//errorMessage!.uppercaseString//不安全的,当errorMessage=nil时,直接报错

var uppercaseErrorMessage = errorMessage?.uppercaseString//uppercaseErrorMessage是可选型
if let errorMessage = errorMessage?.uppercaseString{
    errorMessage
}
var errorMessage:String? = nil
let message: String
if let errorMessage = errorMessage{
    message = errorMessage
}else{
    message = "No error"
}

let message2 = errorMessage == nil ? "No error" : errorMessage
let message3 = errorMessage ?? "No error"//message3想取errorMessage的值,取不到,就显示"No error"

元祖可选型

var error1:(errorCode: Int, errorMessage: String?) = (404, "No found")
error1.errorMessage = nil
error1
var error2:(errorCode: Int, errorMessage: String)? = (404, "No found")
var error3:(errorCode: Int, errorMessage: String?)? = (404, "No found")
var ageInput: String = "12"
var age = Int(ageInput)
if let age = Int(ageInput) where age < 20{
    print("teenager")
}
var greeting = "Hello"
greeting.rangeOfString("ll")//2..<4
greeting.rangeOfString("oo")//nil

隐式可选型

var errorMessage: String! = nil
errorMessage = "Not found"//使用前必须赋值,不然会报错
"The message is " + errorMessage
class City {
    let cityName:String
    unowned var country:Country//unowned防治内存泄漏
    init( cityName:String, country:Country){
        self.cityName = cityName
        self.country = country
    }
}
class Country {
    let countryName:String
    var capitalCity:City!
    init( countryName:String, capitalCity:String){
        self.countryName = countryName
        self.capitalCity = City(cityName: capitalCity, country: self)
    }
    func showInfo(){
        print("This is \(countryName).")
        print("The capital is \(capitalCity.cityName).")
    }
}
let china = Country(countryName: "China", capitalCity: "Beijing")
china.showInfo()

你可能感兴趣的:(可选型)