Swift Enumeration order and comparison

后端 未结 4 909
故里飘歌
故里飘歌 2021-02-18 15:59

I\'ve had trouble finding/understanding documentation on how to compare enums in Swift by their order of definition. Specifically when I create an enumeration such as



        
4条回答
  •  耶瑟儿~
    2021-02-18 16:08

    So long as you give your enum an underlying type, it’ll conform to the protocol RawRepresentable.

    This means you can write a generic comparison operator for any type that is raw representable, and has a raw type that is comparable, like so:

    func <(a: T, b: T) -> Bool {
        return a.rawValue < b.rawValue
    }
    

    which will mean your enum will automatically have a < operator:

    enum E: Int {  // this would work with Double and String also
        // btw, no need to give a seed value of 0,
        // that happens automatically for Ints
        case A, B, C, D, E
    }
    
    E.A < E.C  // returns true
    

    The only bit of boilerplate you’ll still have to do is tag your enum as Comparable in case you want to use it with generic algorithms that require that:

    extension E: Comparable { }
    // (no need for anything else - requirements are already fulfilled)
    
    let a: [E] = [.C, .E, .A]
    let b = sorted(a)
    // b will now be [.A, .C, .E]
    

    Making it conform to Comparable will also give it <=, >, and >= operators automatically (supplied by the standard library).

提交回复
热议问题