Comparing two enum variables regardless of their associated values

后端 未结 3 1483
野趣味
野趣味 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-19 16:52

    Just confirm to Equatable like below

    extension DataType: Equatable {
        static func == (lhs: DataType, rhs: DataType) -> Bool {
            switch (lhs, rhs) {
            case (.One, .Two), (.Two, .One):
                return false
            case (.One, .One), (.Two, .Two):
                return true
            }
        }
    }
    

    If you don't want to implement Equatable just move content into instance method:

    extension DataType{
        func isSame(_ other: DataType) -> Bool {
            switch (self, other) {
            case (.One, .Two), (.Two, .One):
                return false
            case (.One, .One), (.Two, .Two):
                return true
            }
        }
    }
    

    Use:

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

提交回复
热议问题