欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

swift 隐式可选型实例详解

程序员文章站 2023-12-22 08:28:22
1、隐式可选型的基本使用 var errormessage: string? = nil errormessage = "not found" "th...

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()

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

上一篇:

下一篇: