10

このコードを 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

どちらもswift 4.1を使用していますが、

xcode 9.3では 、配列のサイズは4です

xcode 10 beta 3では、 配列のサイズは0です

私はこれをまったく理解していません。

4

3 に答える 3

2

これに対する解決策は、Xcode 10 および Swift 4.2 以降の場合です。

ステップ 1: Protocol EnumIterable を作成します。

protocol EnumIterable: RawRepresentable, CaseIterable {
    var indexValue: Int { get }
}

extension EnumIterable where Self.RawValue: Equatable {
    var indexValue: Int {
        var index = -1
        let cases = Self.allCases as? [Self] ?? []
        for (caseIndex, caseItem) in cases.enumerated() {
            if caseItem.rawValue == self.rawValue {
                index = caseIndex
                break
            }
        }
        return index
    }
}

ステップ 2: EnumIterator プロトコルを列挙型に拡張します。

enum Colors: String, EnumIterable {
    case red = "Red"
    case yellow = "Yellow"
    case blue = "Blue"
    case green = "Green"
}

ステップ 3: hashValue のように indexValue プロパティを使用します。

Colors.red.indexValue
Colors.yellow.indexValue
Colors.blue.indexValue
Colors.green.indexValue

サンプル Print ステートメントと出力

print("Index Value: \(Colors.red.indexValue), Raw Value: \(Colors.red.rawValue), Hash Value: \(Colors.red.hashValue)")

出力: "インデックス値: 0、生の値: 赤、ハッシュ値: 1593214705812839748"

print("Index Value: \(Colors.yellow.indexValue), Raw Value: \(Colors.yellow.rawValue), Hash Value: \(Colors.yellow.hashValue)")

出力: "インデックス値: 1、生の値: 黄色、ハッシュ値: -6836447220368660818"

print("Index Value: \(Colors.blue.indexValue), Raw Value: \(Colors.blue.rawValue), Hash Value: \(Colors.blue.hashValue)")

出力: "インデックス値: 2、生の値: 青、ハッシュ値: -8548080225654293616"

print("Index Value: \(Colors.green.indexValue), Raw Value: \(Colors.green.rawValue), Hash Value: \(Colors.green.hashValue)") 

出力: 「インデックス値: 3、生の値: 緑、ハッシュ値: 6055121617320138804」

于 2019-02-06T07:39:39.453 に答える