打印可选值的第二种方法是正确的,但是有没有更短的方法可以编写具有相同效果的代码? IE。在解开该值之前,我们检查它是否为零。
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)")
}
}
最佳答案
最短的是在 optional 上使用map
:
var city : String?
func printCityName() {
let name = "NY"
city.map{ print("Name of the city is \(name + $0)") }
}
或者 guard 也很好:
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)") }
}
没有警告
关于ios - Swift 字符串附加可选的 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32445359/