简体   繁体   English

Swift String附加可选的nil

[英]Swift String appending with optional nil

The second way of printing an optional value is correct, but is there any shorter way to write code with the same effect? 打印可选值的第二种方法是正确的,但是有没有更短的方法编写具有相同效果的代码? Ie Where before unwrapping the value we check if its 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)")
    }
}

Shortest would be with map on the Optional: 最短的是可选map上的map

var city : String?

func printCityName() {
    let name = "NY"
    city.map{ print("Name of the city is \(name + $0)") }
}

Or guards are nice too: 或后卫也很好:

func printCityName(){
    let name = "NY"
    guard let city = city else { return }
    print("Name of the city is \(name + city)")
}

Your code was alright though, a more readable version is always better when it does the same. 不过,您的代码还不错,如果这样做的话,可读性更好的版本总是更好。 One thing to mention: You don't have to use a different name for the variable in the if let : 要提及的一件事: if letif let中,您不必为变量使用其他名称:

func printCityName(){
    let name = "NY"
    if let city = city {
        print("Name of the city is \(name + city)")
    }
}

EDIT: 编辑:

If you don't like to use _ = every time with the first version, you can extend Optional : 如果您不希望在第一个版本中每次都使用_ = ,则可以扩展Optional

extension Optional {
    func with(@noescape f: Wrapped throws -> Void) rethrows {
        _ = try map(f)
    }
}

which makes it possible to do this: 这样就可以做到这一点:

func printCityName() {
    let name = "NY"
    city.with{ print("Name of the city is \(name + $0)") }
}

without a warning 没有警告

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

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