【问题标题】:How to extend the Swift Dictionary type to return a non-empty String or nil如何扩展 Swift Dictionary 类型以返回非空字符串或 nil
【发布时间】:2015-05-21 17:16:30
【问题描述】:

我正在写一个extension 到Dictionary,这样当我给它一个String 键时,它只会返回一个String,只有当与键关联的值是非- nil 且不为空。

extension Dictionary {

    subscript(key: String) -> String? {
        if let string = super.subscript(key) {
            if string.isEmpty == false {
                return string
            }
        }
        return nil
    }

}

但是,在if let string = super.subscript(key) { 行,我收到以下编译错误,我不知道这是什么意思——Google 结果也没有解释它:

下标元素类型应为 ->

我这样做是因为我正在使用一个返回 JSON 的 API,其中键的值可能是一个空字符串——根据我们的要求,这对应用程序来说是一个无效值,因此与 nil 一样好。

当然,更长的方法可以,但我正在寻找一种方法来缩短它。

if let value = dict["key"] as? String {
    if value.isEmpty == false {
        // The value is non-nil and non-empty.
    }
}

【问题讨论】:

  • 不要这样做。相反,请if let value = dictionary["key"] as? String where !value.isEmpty { ... }
  • @mattt 听起来不错,把它作为答案让我接受吗?
  • Apple 有一篇关于可能相关主题的有趣文章:developer.apple.com/swift/blog/?id=12
  • 顺便说一句,这里的一个技术问题是您假设字典键是字符串,但不必如此。而且您不能定义仅适用于通用占位符的受限类型的扩展方法。
  • 感谢@MartinR 的提醒。猜猜我会走马特的路。

标签: ios swift cocoa cocoa-touch foundation


【解决方案1】:

你会认为这很愚蠢,但我的建议是:或多或少地做你正在做的事情,但将它封装为一个单独的函数,而不是试图处理定义一个新函数的含义subscript:

extension Dictionary {
    func nes(key:Key) -> String? {
        var result : String? = nil
        if let s = self[key] as? String {
            if !s.isEmpty {
                result = s
            }
        }
        return result
    }
}

(nes 代表“非空字符串”。)

现在将其称为d.nes("foo")。

【讨论】:

  • 我已经写了一个全局函数来做同样的事情,但我仍然不认为这很傻!
  • 实际上全局函数将是我的第一个建议! :))) 但后来我对自己说,不,让我们为自己保存一个参数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-20
  • 2015-10-28
  • 2020-09-15
  • 2018-03-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多