当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Swift Dictionary compactMapValues(_:)用法及代码示例


实例方法

compactMapValues(_:)

返回一个新字典,该字典仅包含具有非 nil 值的键值对作为给定闭包转换的结果。

声明

func compactMapValues<T>(_ transform: (Value) throws -> T?) rethrows -> Dictionary<Key, T>
Key 符合 Hashable 时可用。

返回值

包含此字典的键和非 nil 转换值的字典。

参数

transform

转换值的闭包。 transform 接受字典的每个值作为其参数,并返回相同或不同类型的可选转换值。

详述

当您的转换产生可选值时,使用此方法接收具有非可选值的字典。

在此示例中,请注意将mapValuescompactMapValues 与返回可选Int 值的转换一起使用的结果不同。


let data = ["a": "1", "b": "three", "c": "///4///"]


let m: [String: Int?] = data.mapValues { str in Int(str) }
// ["a": Optional(1), "b": nil, "c": nil]


let c: [String: Int] = data.compactMapValues { str in Int(str) }
// ["a": 1]

可用版本

iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+

相关用法


注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 Dictionary compactMapValues(_:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。