打印可选值的第二种方法是正确的,但有没有更短的方法来编写具有相同效果的代码?即在解开价值之前,我们检查它是否为零。
var city:String?
func printCityName(){
let name = "NY"
//Fails (First Way)
print("Name of the city is \(name + city)")
//Success (Second Way)
if let cityCheckConstant = city {
print("Name of the city is \(name + cityCheckConstant)")
}
}
答案 0 :(得分:0)
最短的将是map
在Optional:
var city : String?
func printCityName() {
let name = "NY"
city.map{ print("Name of the city is \(name + $0)") }
}
或者警卫也很好:
func printCityName(){
let name = "NY"
guard let city = city else { return }
print("Name of the city is \(name + city)")
}
你的代码没问题,但是当它做同样的事情时,更可读的版本总是更好。有一点需要提及:您不必在if let
:
func printCityName(){
let name = "NY"
if let city = city {
print("Name of the city is \(name + city)")
}
}
编辑:
如果您不希望每次使用_ =
第一个版本,都可以延长Optional
:
extension Optional {
func with(@noescape f: Wrapped throws -> Void) rethrows {
_ = try map(f)
}
}
可以做到这一点:
func printCityName() {
let name = "NY"
city.with{ print("Name of the city is \(name + $0)") }
}
没有警告