實例方法
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(_:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。