实例方法
compact
compactMapValues(_:)
返回一个新字典,该字典仅包含具有非
nil
值的键值对作为给定闭包转换的结果。声明
func compactMapValues<T>(_ transform: (Value) throws -> T?) rethrows -> Dictionary<Key, T>
当
Key
符合 Hashable
时可用。返回值
包含此字典的键和非 nil
转换值的字典。
参数
transform
转换值的闭包。
transform
接受字典的每个值作为其参数,并返回相同或不同类型的可选转换值。
详述
当您的转换产生可选值时,使用此方法接收具有非可选值的字典。
在此示例中,请注意将mapValues
和compactMapValues
与返回可选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+
相关用法
- Swift Dictionary compactMap(_:)用法及代码示例
- Swift Dictionary contains(where:)用法及代码示例
- Swift Dictionary allSatisfy(_:)用法及代码示例
- Swift Dictionary values用法及代码示例
- Swift Dictionary dropFirst(_:)用法及代码示例
- Swift Dictionary firstIndex(where:)用法及代码示例
- Swift Dictionary first(where:)用法及代码示例
- Swift Dictionary merge(_:uniquingKeysWith:)用法及代码示例
- Swift Dictionary subscript(_:default:)用法及代码示例
- Swift Dictionary isEmpty用法及代码示例
- Swift Dictionary reduce(_:_:)用法及代码示例
- Swift Dictionary suffix(from:)用法及代码示例
- Swift Dictionary subscript(_:)用法及代码示例
- Swift Dictionary init(uniqueKeysWithValues:)用法及代码示例
- Swift Dictionary makeIterator()用法及代码示例
- Swift Dictionary randomElement()用法及代码示例
- Swift Dictionary init(grouping:by:)用法及代码示例
- Swift Dictionary dropLast(_:)用法及代码示例
- Swift Dictionary min(by:)用法及代码示例
- Swift Dictionary max(by:)用法及代码示例
- Swift Dictionary updateValue(_:forKey:)用法及代码示例
- Swift Dictionary removeValue(forKey:)用法及代码示例
- Swift Dictionary map(_:)用法及代码示例
- Swift Dictionary forEach(_:)用法及代码示例
- Swift Dictionary index(forKey:)用法及代码示例
注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 Dictionary compactMapValues(_:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。