iOS开发

Swift中带参枚举使用if的问题

2019-10-28  本文已影响0人  seasonZhu

最近写个新功能,是有关输入的,主要是用于限制输入的字符类型.

public enum InputCharsType {
        case numeral
        case letter
        case numerallAndXx
        case numeralAndLetter
        case all
        case custom(String)
}

然后还有一个扩展,用于表示每一种状态能够输入的字符类型

extension InputCharsType {
    public var chars: String {
        let chars: String
        switch self {
        case .numeral:
            chars = "0123456789"
        case .letter:
            chars = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"
        case .numerallAndXx:
            chars = "0123456789Xx"
        case .numeralAndLetter:
            chars = "0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"
        case .all:
            chars = ""
        case .custom(let string):
            chars = string
        }
        return chars
    }
}

看看挺满意的,我特地预留了一个custom状态可以在传参的时候可以自定义输入的字符类型,这样枚举就覆盖了所有情况,想想很好.

然后,用的时候,有的时候只想通过if与else来做一个判断

if inputCharsType = .all {

}

直接报错了,原因很简单,因为包含一个带参的枚举,不知道如何判断这个枚举类型.

我心想,既然不让使用if 那使用switch总可以吧

switch inputCharsType: {
  case .all:
    break
  default:
    break
}

看看就觉得很傻,而且每次做判断的时候都这么写一次switch实在很累.

闲下来时候的我想了想 != 的本质,能够使用不等或者说用等号的本质就是遵守Equatable协议啊!
嗯,说干就干:

extension InputCharsType: Equatable {
    public static func == (lhs: InputCharsType, rhs: InputCharsType) -> Bool {
        switch (lhs, rhs) {
        case (.numeral, .numeral):
            return true
        case (.letter, .letter):
            return true
        case (.numerallAndXx, .numerallAndXx):
            return true
        case (.numeralAndLetter, .numeralAndLetter):
            return true
        case (.all, .all):
            return true
        case (.custom(let string1), .custom(let string2)):
            return string1 == string2
        default:
            return false
        }
    }
}

完美,这样就可以使用等号与不等号了.

所以说,Swift如果发现自己的枚举,类,结构体不满足某些特性的时候,想想可不可以自己创造条件,遵守底层的协议去满足功能.

上一篇下一篇

猜你喜欢

热点阅读