繁体   English   中英

Swift String附加可选的nil

[英]Swift String appending with optional nil

打印可选值的第二种方法是正确的,但是有没有更短的方法编写具有相同效果的代码? 即在解开值之前,我们先检查它是否为零。

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)")
    }
}

最短的是可选map上的map

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 letif 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)") }
}

没有警告

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM