当前位置: 移动技术网 > 移动技术>移动开发>IOS > swift 隐式可选型实例详解

swift 隐式可选型实例详解

2019年07月24日  | 移动技术网移动技术  | 我要评论

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

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网