Swift中的Optional

2019-06-29  本文已影响0人  盖小聂

1、隐式解包Optional
2、Optional Chaining
3、多重Optional
4、Optional Map
5、JSON

1、隐式解包Optional
var maybeObject: MyClass!
@IBOutlet weak var button: UIButton!
2、Optional Chaining
//toyName的类型为String?,这是由于在Optional Chaining中我们在任意一个?.的时候都可能遇到nil而提前返回,
//这个时候当然就只能拿到nil了
let toyName = xiaoming.pet?.toy?.name 
if let toyName = xiaoming.pet?.toy?.name {    
  //太好了,小明既有宠物,而且宠物还正好有个玩具
}
3、多重Optional
var aNil: String? = nil
var anotherNil: String?? = aNil
var literalNil: String?? = nil
if let a = anotherNil {    
  print(“anotherNil”)
}
if let b = literalNil {    
  print(“literalNil)
}

这样的代码只能输出anotherNil

4、Optional Map
let arr = [1,2,3]
let doubled = arr.map {    
  $0 * 2
}
let num: Int? = 3
let result = num.map {    
  $0 * 2
}
5、JSON
if let value = JSON(json)[“menu”][“popup”][“menuitem”][0][“value”].string {    
  print(value)
} //json is a AnyObject from JSONObjectWithData
上一篇下一篇

猜你喜欢

热点阅读