Swift String附加可选的nil

时间:2023-01-05 21:18:08

The second way of printing an optional value is correct, but is there any shorter way to write code with the same effect? I.e. 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)")
    }
}

1 个解决方案

#1


0  

Shortest would be with map on the Optional:

最短的将是可选的地图:

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中,您不必为变量使用不同的名称:

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

没有警告

#1


0  

Shortest would be with map on the Optional:

最短的将是可选的地图:

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中,您不必为变量使用不同的名称:

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

没有警告