ios - Swift 字符串附加可选的 nil

标签 ios string swift

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

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

最佳答案

最短的是在 optional 上使用map:

var city : String?

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

或者 guard 也很好:

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

没有警告

关于ios - Swift 字符串附加可选的 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32445359/

相关文章:

iphone - iPhone/iOS popViewControllerAnimated不刷新屏幕

c# - 比较字符串数组的最佳方法(自定义命令行命令)

Python正则表达式,删除除连字符以外的所有标点符号用于unicode字符串

ios - PromiseKit 取消 promise

ios - 自定义 UITextField 的边框

objective-c - 如何阻止 UIScrollView 从其父 View 获取触摸事件?

ios - NSUserDefaults 会从 TestFlight 持续到最终的 App Store 版本吗?

ios - UIActivityIndi​​cator 不会在 iOS 中停止

string - 简单的字符串哈希函数

swift - 更短的通用签名