kr1*_*hna 10 xcode swift xcode10
我在xcode 9.3和xcode 10 beta 3游乐场中运行此代码
import Foundation
public protocol EnumCollection: Hashable {
static func cases() -> AnySequence<Self>
}
public extension EnumCollection {
public static func cases() -> AnySequence<Self> {
return AnySequence { () -> AnyIterator<Self> in
var raw = 0
return AnyIterator {
let current: Self = withUnsafePointer(to: &raw) { $0.withMemoryRebound(to: self, capacity: 1) { $0.pointee } }
guard current.hashValue == raw else {
return nil
}
raw += 1
return current
}
}
}
}
enum NumberEnum: EnumCollection{
case one, two, three, four
}
Array(NumberEnum.cases()).count
Run Code Online (Sandbox Code Playgroud)
即使两者都使用swift 4.1,他们也会给我不同的结果
在xcode 9.3 上,数组的大小为4
在xcode 10 beta 3 上,数组的大小为0
我根本不明白这一点.
Mar*_*n R 18
这是一种未记录的方法来获取所有枚举值的序列,并且只是偶然使用早期的Swift版本.它依赖于枚举值的哈希值是连续整数,从零开始.
这绝对不适用于Swift 4.2(即使在Swift 4兼容模式下运行),因为哈希值现在总是随机化的,请参阅SE-0206 Hashable增强功能:
为了使哈希值不太可预测,标准哈希函数默认使用每执行随机种子.
您可以验证
print(NumberEnum.one.hashValue)
print(NumberEnum.two.hashValue)
Run Code Online (Sandbox Code Playgroud)
这不会不打印0和1在Xcode 10,但一些其他值这也与每个程序运行而有所不同.
有关正确的Swift 4.2/Xcode 10解决方案,请参阅如何使用String类型枚举枚举?:
extension NumberEnum: CaseIterable { }
print(Array(NumberEnum.allCases).count) // 4
Run Code Online (Sandbox Code Playgroud)