swift - Swift 4 中的过滤字典在 Xcode 中失败,但在 Playground 中成功

标签 swift xcode9-beta swift4

在 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

下更改它

enter image description here

基金会文档摘录: 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/

相关文章:

ios - Mapbox Callout View 在顶部的正确定位

ios - Firebase 和 Alamofire Url TableViewCell 图像加载问题 Swift 4

ios - UINavigationBar 标题颜色

swift - AVPlayerItemVideoOutput.copyPixelBuffer 因 EXC_BAD_ACCESS 失败

ios - 在 Xcode 9(测试版)中将 pod 与 Playgrounds 结合使用

ios - 永远不会调用 UITextField drawTextInRect

Xcode 9 Beta - 无法添加新的 Playground 页面

ios - 与输入相比,谷歌地图显示不同的位置

ios - 在 itunesconnect 上看不到构建

ios - 未调用 HMAccessoryDe​​legate 方法