【发布时间】: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