Swift Enumeration order and comparison

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

    This is to some extent the same answer as the OP proposed himself. It does involve a bit of boilerplate code for every enum that you want to be comparable, but I prefer this than having some external magic function that provides comparable to all enums. That can cause problems if you do a quick copy-and-paste from one program to another, and then the enum doesn't work and you can't remember why.

    public enum LogLevel: Int, Comparable {
        case verbose
        case debug
        case info
        case warning
        case error
        case severe
    
        // Implement Comparable
        public static func < (a: LogLevel, b: LogLevel) -> Bool {
            return a.rawValue < b.rawValue
        }
    }
    

    EDIT:

    This is in response to a comment by @JasonMoore.

    Comparable does not require ==. That is required by Equatable, and the Swift standard library automatically provides Equatable for most kinds of enums.

    http://www.jessesquires.com/blog/swift-enumerations-and-equatable/

    As for >, <= and >=, the Apple documentation says that they are required by Comparable, but that a default implementation is provided (based on use of == and <, I assume).

    https://developer.apple.com/documentation/swift/comparable

    Here's a bit of code that I ran in the IBM Swift Sandbox - it compiles and runs fine with the above definition.

    let a : LogLevel = LogLevel.verbose
    let b : LogLevel = LogLevel.verbose
    let c : LogLevel = LogLevel.warning
    
    print(a == b)  // prints true
    print(a > c)  // prints false
    print(a <= c)  // prints true
    

提交回复
热议问题