Swift enum with custom initializer loses rawValue initializer

后端 未结 6 1492
长发绾君心
长发绾君心 2021-01-30 12:07

I have tried to boil this issue down to its simplest form with the following.

Setup

Xcode Version 6.1.1 (6A2008a)

An enum defined in MyEnum.swift

6条回答
  •  盖世英雄少女心
    2021-01-30 12:46

    This works for Swift 4 on Xcode 9.2 together with my EnumSequence:

    enum Word: Int, EnumSequenceElement, CustomStringConvertible {
        case apple, cat, fun
    
        var description: String {
            switch self {
            case .apple:
                return "Apple"
            case .cat:
                return "Cat"
            case .fun:
                return "Fun"
            }
        }
    }
    
    let Words: [String: Word] = [
        "A": .apple,
        "C": .cat,
        "F": .fun
    ]
    
    extension Word {
        var letter: String? {
            return Words.first(where: { (_, word) -> Bool in
                word == self
            })?.key
        }
    
        init?(_ letter: String) {
            if let word = Words[letter] {
                self = word
            } else {
                return nil
            }
        }
    }
    
    for word in EnumSequence() {
        if let letter = word.letter, let lhs = Word(letter), let rhs = Word(letter), lhs == rhs {
            print("\(letter) for \(word)")
        }
    }
    

    Output

    A for Apple
    C for Cat
    F for Fun
    

提交回复
热议问题