【问题标题】:Unwrap String and check emptiness in the same if statement在同一个 if 语句中打开字符串并检查是否为空
【发布时间】:2015-03-20 10:44:16
【问题描述】:

我想实现这个

if let large = imageLinks.large {

    if !large.isEmpty {

        result = large
    }
}

在单个 if 语句中,类似这样的内容(这不会编译)

if let large = imageLinks.large where !large.isEmpty {

    result = large       
}

有可能吗?

【问题讨论】:

  • 您的代码在我看来应该可以工作。你遇到了什么错误?
  • @Christian 我已经更新到 Swift 1.2,现在可以使用了。

标签: swift


【解决方案1】:

这还不可能。 在 swift 的实际版本中,if let 语句非常糟糕。

但是使用 Swift 1.2(它将在 Xcode 6.3 中可用)。 您将能够做到这一点:

(SWIFT 1.2)

if let large = imageLinks.large where !large.isEmpty {

    result = large       
}

但现在你不能。 您可以执行以下操作:

if  imageLinks.large != nil && !imageLinks.large!.isEmpty {
   result = large!;
}

注意: Swift 使用“懒惰评估” 如果第一部分imageLinks.large != nil 为假,则不会评估第二部分,因此不会崩溃。

但我不觉得这个解决方案很漂亮(展开的力太大)。

【讨论】:

    【解决方案2】:

    在 Swift 4.4 中,泛型来拯救 \o/

    public extension Optional where Wrapped == String {
        var isEmptyOrNil: Bool { (self ?? "").isEmpty }
    }
    

    用法

    if nameField.text.isEmptyOrNil {
        //doSomething...
    }
    

    【讨论】:

      【解决方案3】:

      在 Swift 1.1 中

      如果您不喜欢强制展开,您可以:

      if let large = imageLinks.large?.isEmpty == false ? imageLinks.large : nil {
          result = large
      }
      

      反正也不是很漂亮:(

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-02
        • 1970-01-01
        • 2021-06-28
        • 2018-03-16
        • 2012-11-26
        • 2013-09-11
        相关资源
        最近更新 更多