在 Swift 4 Playground 中,这段代码:
let time = 1234
let description: String? = nil
let keyed: [String : Any?] = [
"time": time,
"description": description
]
let filtered: [String : String] = keyed
.filter{ _, value in value != nil }
.mapValues { value in return String(describing: value!) }
print(keyed)
print(filtered)
产生这个输出:
["description": nil, "time": Optional(1234)]
["time": "1234"]
这正是我想要的(只有键值对,其中原始值不是 nil
,值被解包并转换为字符串)。然而,在 Xcode 9 (beta 3) 中,我的构建失败并显示 'filter' is unavailable
。这是测试版 ¯\_(ツ)_/¯
之类的东西,还是我遗漏了什么?
最佳答案
您使用的是 Swift 3.2 而不是 Swift 4。
您可以在目标的 Build Options
> Swift Compiler - Language
> Swift Language Version
基金会文档摘录: https://developer.apple.com/documentation/swift/dictionary/2903389-filter?changes=latest_minor
func filter(_ isIncluded: (Dictionary.Element) throws -> Bool) rethrows -> [Dictionary.Key : Dictionary.Value]
Xcode 9.0+
关于swift - Swift 4 中的过滤字典在 Xcode 中失败,但在 Playground 中成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46632714/