溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

swift 隱式可選型實例詳解

發布時間:2020-10-02 01:42:44 來源:腳本之家 閱讀:172 作者:追到夢的魔術師 欄目:移動開發

1、隱式可選型的基本使用

var errorMessage: String? = nil
errorMessage = "Not Found"
"The message is " + errorMessage!

隱式可選型的定義

var errorMessage: String! = nil
errorMessage = "Not Found"
"The message is " + errorMessage

隱式可選型不需要解包,所以隱式可選型容易出錯

以上程序當errorMessage為nil時程序會報錯

2、隱式可選型的實際應用

// 主要應用在類的成員變量的初始化上
class City{

  let cityName: String
  unowned var country: Country
  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()

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女