如何将 Swift 字典类型扩展为 return 非空字符串或 nil

How to extend the Swift Dictionary type to return a non-empty String or nil

我正在写一个 extensionDictionary 这样当我给它一个 String 键时,它会 return 我一个 String仅当与键关联的值是 非零且不为空时 .

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 结果解释它:

Expected -> for subscript element type

我这样做是因为我正在使用一个 API,它 return 是一个 JSON,其中一个键的值可能是一个空字符串——这是一个无效的值该应用程序符合我们的要求,因此与零一样好。

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

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

你会认为这很愚蠢,但我的建议是:或多或少地做你正在做的事情,但将它封装为一个单独的函数,而不是试图处理定义的含义一个新的 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 代表 "non-empty string"。)

现在可以这样称呼它 d.nes("foo")