Xcode 9 and Xcode 10 giving different results, even with same swift version

前端 未结 3 1915
青春惊慌失措
青春惊慌失措 2020-12-06 17:42

I am running this code in both xcode 9.3 and xcode 10 beta 3 playground

import Foundation

public protocol EnumCollection: Hashable {
    static func cases()         


        
3条回答
  •  借酒劲吻你
    2020-12-06 18:30

    That is an undocumented way to get a sequence of all enumeration values, and worked only by chance with earlier Swift versions. It relies on the hash values of the enumeration values being consecutive integers, starting at zero.

    That definitely does not work anymore with Swift 4.2 (even if running in Swift 4 compatibility mode) because hash values are now always randomized, see SE-0206 Hashable Enhancements:

    To make hash values less predictable, the standard hash function uses a per-execution random seed by default.

    You can verify that with

    print(NumberEnum.one.hashValue)
    print(NumberEnum.two.hashValue)
    

    which does not print 0 and 1 with Xcode 10, but some other values which also vary with each program run.

    For a proper Swift 4.2/Xcode 10 solution, see How to enumerate an enum with String type?:

    extension NumberEnum: CaseIterable  { }
    print(Array(NumberEnum.allCases).count) // 4
    

提交回复
热议问题