Ios 带可选nil的Swift字符串

Ios 带可选nil的Swift字符串,ios,string,swift,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 = ci

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

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)")
    }
}
最短的是可选的地图:

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

编辑:

如果不希望在第一个版本中每次都使用=,可以扩展可选的:

var city : String?

func printCityName() {
    let name = "NY"
    city.map{ print("Name of the city is \(name + $0)") }
}
这就有可能做到这一点:

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

在没有警告的情况下

您可以使用if city!=无您不需要将unwrapped可选值指定给新常量。您可以编写=city.flatMap{printName of the city is\name+$0}Swift 2,但我始终希望您的代码支持此模糊版本。城市=零,很简单。当我尝试使用flatMap时,$0抛出错误,并且自动更正将其更改为city.flatMap{printName of the city is name+$0 as String}@andyPaul:那么city不是字符串?。也许是一根线@马丁纳,我错了,是弦。后来,我在操场上换了一条绳子。如果让city=city,将创建一个常量,但它将使代码更具可读性。那么,如果城市nil会更好,因为它不会创建常量。@Paulw11在评论中提到questions@andyPaul我真的不认为编译器是那么糟糕,它总是复制值时,如果让展开。我们不应该为这种伪微优化牺牲清晰度。备注:city.map{…}语句在Xcode 7 beta 6中导致表达式结果未使用警告返回类型是?又名可选无效。我不知道这是故意的还是一个bug,但它可以用=city.map{…}沉默。@MartinR是的,这不是bug,返回类型真的是?因为打印返回。我没看到,因为我在操场上。“是的,{有点难看。”马丁纳更新了我的答案:D
func printCityName() {
    let name = "NY"
    city.with{ print("Name of the city is \(name + $0)") }
}