Swift-可选型

  1. 可选型的声明
var errorCode: String? = "404" //表示变量可以为空值,通常用var声明
print(errorCode) // 输出:optional("404")
  1. 可选型的基本用法
"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!"  //更简洁的写法
}
  1. 可选型更多用法
// 区别下列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. 隐式可选型的用例
//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: "北京")

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