Swift String附加可选的nil

时间:2015-09-07 20:03:24

标签: ios string swift

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

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 个答案:

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

没有警告