您如何检查可选字符串的长度?

How do you inspect an Optional-String's length?

class PersonEntry: NSObject {
  var firstName: String?
  var lastName: String?
}

//This errors
if (self.person.firstName?.isEmpty) {
          println("Empty")
}

//Compiler auto-correction is this
if ((self.model.firstName?.isEmpty) != nil) {
          println("Empty")
}

我知道可选链接 returns 是一种可选类型。所以我想我的问题是,如何打开一个可选字符串来检查它的长度,而不会有崩溃的风险?

我假设如果 属性 是 nil 那么你想认为它是空的 - 在这种情况下你可以将 nil 合并运算符与 if 语句的第一个版本结合使用:

if self.person.firstName?.isEmpty ?? true {
          println("Empty")
}

如果 firstName 为 nil,则表达式的计算结果为合并运算符 true 的右侧 - 否则它的计算结果为 isEmpty 属性 的值.


参考文献:

Nil Coalescing Operator

Optional Chaining

又一招。

var str: String?
str = "Hello, playground"

println(count(str ?? ""))