Comparing two enum variables regardless of their associated values

后端 未结 3 1480
野趣味
野趣味 2021-01-19 16:10

Consider this enum:

enum DataType {
    case One (data: Int)
    case Two (value: String)
}

Swift has pattern matching to compare an enum w

3条回答
  •  失恋的感觉
    2021-01-19 16:46

    Updated approach:

    I think there's no native support for this. But you can achieve it by defining a custom operator (preferrably by using a protocol, but you can do it directly as well). Something like this:

    protocol EnumTypeEquatable {
        static func ~=(lhs: Self, rhs: Self) -> Bool
    }
    
    extension DataType: EnumTypeEquatable {
        static func ~=(lhs: DataType, rhs: DataType) -> Bool {
            switch (lhs, rhs) {
            case (.one, .one), 
                 (.two, .two): 
                return true
            default: 
                return false
            }
        }
    }
    

    And then use it like:

    let isTypeEqual = DataType.One(value: 1) ~= DataType.One(value: 2)
    print (isTypeEqual) // true
    



    Old approach:

    protocol EnumTypeEquatable {
        var enumCaseIdentifier: String { get }
    }
    
    extension DataType: EnumTypeEquatable {
        var enumCaseIdentifier: String {
            switch self {
            case .one: return "ONE"
            case .two: return "TWO"
            }
        }
    }
    
    func ~=(lhs: T, rhs: T) -> Bool where T: EnumTypeEquatable {
        return lhs.enumCaseIdentifier == rhs.enumCaseIdentifier
    }
    

    The older version depends on Runtime and might be provided with default enumCaseIdentifier implementation depending on String(describing: self) which is not recommended. (since String(describing: self) is working with CustromStringConvertible protocol and can be altered)

提交回复
热议问题