Swift Enumeration order and comparison

后端 未结 4 833
故里飘歌
故里飘歌 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:23

    In newer versions of Swift you can create a protocol to achieve this, without the need for generic globals. This also gives you the ability to choose which enums this affects.

    /// Allows a raw enum type to be compared by the underlying comparable RawValue
    public protocol RawComparable : Comparable where Self : RawRepresentable, RawValue: Comparable {
    }
    
    extension RawComparable {
        public static func < (lhs: Self, rhs: Self) -> Bool {
            return lhs.rawValue < rhs.rawValue
        }
    }
    

    To use this it's as simple as adding the RawComparable protocol to the enum type:

    enum EnumType : Int, RawComparable {
        case First = 0, Second, Third
    }
    

提交回复
热议问题