var errorCode: String? = "404" //表示變量可以為空值,通常用var聲明
print(errorCode) // 輸出:optional("404")
可選型的基本用法
"The errorCode is " + errorCode //報錯,可選型不能直接使用
需要用解包(unwrapped)的方式使用
"Hello" + errorCode! //強制解包,有風險性(errorCode可能為nil)
if let errorCode = errorCode { // 推薦用法(“if-let式”解包,建立新的解包常量,可以在大括號內持續使用)
print("The errorCode is " + errorCode)
} // 輸出: The errorCode is 404
//一次性解包多個變量
if let errorCode = errorCode ,
let errorMessage = errorMessage , errorCode == "404"{
print("Page Not Found!")
//可選型鏈
errorCode?.uppercased() //安全解包?
var uppercasedErrorCode = errorCode?.uppercased() //仍然是可選型
//可選型變量賦值給另一個變量
let errorCode1 = errorCode == nil ? "Error!" : errorCode!
let errorCode2 = errorCode ?? "nil-Error!" //更簡潔的寫法
}
可選型更多用法
// 區別下列3中可選型
var error1: (errorCode: Int, errorMessage: String?) = (404, "Not Found")
var error2: (errorCode: Int, errorMessage: String)? = (404, "Not Found")
var error3: (errorCode: Int, errorMessage: String?)? = (404, "Not Found")
//可選型在實際項目中的應用
var ageInput: String = "16"
//隱式可選型
var errorMessage: String! = nil
errorMessage = "Not Found"
print("The message is " + errorMessage)
隱式可選型的用例
//1. 可以存放nil,可以直接使用,不用強制解包
//2. 常用于類的定義中(一開始設置為nil,在初始化后賦值)
var errorMessage: String! = nil
errorMessage = "Not Found"
"The message is " + errorMessage //但是如果是nil,則會直接報錯(不安全)
class City {
let cityName: String
var country: Country
init(cityName: String, country: Country) {
self.cityName = cityName
self.country = country
}
}
class Country {
let countryName: String
var capitalCity: City! //初始化Country需要先初始化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: "中國", capitalCity: "北京")