首页 > swift中关于枚举的问题

swift中关于枚举的问题

enum MenuButtonType:Int{
    case Return = 0, Caterine, AboutUs, Message, Logout
}

有如上枚举,为了代码的可读性,想用上面的枚举给一些类似的按钮做区别。

button.tag = MenuButtonType.Return // swift中比较强调类型 这样的附值是错误的

我暂时的想法是写一个分类

extension UIButton
{
    func transformEnumToTag (type:MenuButtonType)
    {
        switch type
        {
        case .Return:
            self.tag = 0
            ....
        }
    }
}

但是到时候又要转换回来,比较麻烦。
请问有什么好的方法


你这种情况,就应该有一个 MenuButton 去继承 UIButton,然后内部有一个属性是 type。

你这样的解决方式,非常的不优雅、不正确的。


  1. UIButton命名规则加个字符区分

  2. 继承UIButton,加个属性区分


enum MenuButtonType: Int {
    case Return = 0, Caterine, AboutUs, Message, Logout
}

let button = UIButton()
button.tag = MenuButtonType.Return.rawValue
print(button.tag)    //0

你要的是不是这样,加个rawValue就能获取到Return的值

【热门文章】
【热门文章】