結構
Any
AnyHashable
type-erased 可散列值。
聲明
@frozen struct AnyHashable
概述
AnyHashable
類型將相等比較和散列操作轉發到底層可散列值,隱藏包裝值的類型。
在兩種類型(例如 Int
和 NSNumber
)之間可以使用 as
或 as?
進行轉換,AnyHashable
使用 type-erased 值的規範表示,以便實例包裝任一類型的相同值比較相等。例如, AnyHashable(42)
比較等於 AnyHashable(42 as NSNumber)
。
您可以將mixed-type 鍵存儲在字典和其他需要Hashable
一致性的集合中,方法是將mixed-type 鍵包裝在AnyHashable
實例中:
let descriptions: [AnyHashable: Any] = [
42: "an Int",
43 as Int8: "an Int8",
["a", "b"] as Set: "a set of strings"
]
print(descriptions[42]!) // prints "an Int"
print(descriptions[42 as Int8]!) // prints "an Int"
print(descriptions[43 as Int8]!) // prints "an Int8"
print(descriptions[44]) // prints "nil"
print(descriptions[["a", "b"] as Set]!) // prints "a set of strings"
請注意,AnyHashable
不保證它保留包裝值的哈希編碼。不要依賴 AnyHashable
生成此類兼容的哈希,因為它使用的哈希編碼可能會在標準庫的任何兩個版本之間發生變化。
可用版本
iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+
相關用法
- Swift AnyHashable ==(_:_:)用法及代碼示例
- Swift AnyHashable debugDescription用法及代碼示例
- Swift AnyHashable base用法及代碼示例
- Swift AnyHashable description用法及代碼示例
- Swift AnySequence elementsEqual(_:)用法及代碼示例
- Swift AnyCollection min()用法及代碼示例
- Swift AnyBidirectionalCollection elementsEqual(_:)用法及代碼示例
- Swift AnyRandomAccessCollection randomElement(using:)用法及代碼示例
- Swift AnyBidirectionalCollection lexicographicallyPrecedes(_:)用法及代碼示例
- Swift AnyBidirectionalCollection split(separator:maxSplits:omittingEmptySubsequences:)用法及代碼示例
- Swift AnyRandomAccessCollection first(where:)用法及代碼示例
- Swift AnyBidirectionalCollection sorted()用法及代碼示例
- Swift AnyRandomAccessCollection min()用法及代碼示例
- Swift AnySequence shuffled(using:)用法及代碼示例
- Swift AnyBidirectionalCollection shuffled(using:)用法及代碼示例
- Swift AnyRandomAccessCollection prefix(upTo:)用法及代碼示例
- Swift AnyBidirectionalCollection starts(with:)用法及代碼示例
- Swift AnyBidirectionalCollection contains(where:)用法及代碼示例
- Swift AnyCollection allSatisfy(_:)用法及代碼示例
- Swift AnyRandomAccessCollection prefix(through:)用法及代碼示例
- Swift AnyBidirectionalCollection suffix(from:)用法及代碼示例
- Swift AnyCollection compactMap(_:)用法及代碼示例
- Swift AnyIterator suffix(_:)用法及代碼示例
- Swift AnyIterator lexicographicallyPrecedes(_:)用法及代碼示例
- Swift AnySequence joined()用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 AnyHashable。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。