Comparing two enum variables regardless of their associated values

后端 未结 3 1477
野趣味
野趣味 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:37

    This worked for me:

    enum DataType {
        case one (data: Int)
        case two (value: String)
    }
    
    protocol EnumTypeEquatable {
        static func sameType(lhs: Self, rhs: Self) -> Bool
    }
    
    extension DataType: EnumTypeEquatable {
        static func sameType(lhs: DataType, rhs: DataType) -> Bool {
            if let caseLhs = Mirror(reflecting: lhs).children.first?.label, let caseRhs = Mirror(reflecting: rhs).children.first?.label {
                return (caseLhs == caseRhs)
            } else { return false }
        }
    }
    
    let isTypeEqual = DataType.sameType(lhs: .one(data: 1), rhs: .one(data: 2))
    print (isTypeEqual) // true
    

提交回复
热议问题