连接枚举返回类型

时间:2017-09-14 10:17:45

标签: ios swift struct enums

我有一个看起来像这样的枚举:

class CustomButton {
  struct Section {
    enum Root: Int {
      case rootFirst, rootSecond, rootThird
    }

    enum Top: Int {
      case topFirst, topSecond, topThird
    }
  }

  var type: Any?
}

我有来自不同CustomButton的不同Section,我希望能够通过执行CustomButton之类的操作来检测每个customButton.type的类型。

现在我可以通过在type类上创建CustomButton变量,但Any为var类型来实现,因为它应该存储不同的按钮类型。问题是每次我得到type变量时,我都要检查我正在使用哪种类型的按钮,类似type(of: type),然后将Any类型转换为什么type(of: buttonType)正在举报,以便我可以根据类型访问topFirstrootSecond

有更简单的方法吗?我打赌有,但经过几个小时的研究后我什么都没找到,而且我对Swift也很新。

提前致谢!

2 个答案:

答案 0 :(得分:2)

我认为你的结构过于复杂,也许我误解了它,但我你想要做的是:

class CustomButton {

    enum Section { // Not a `struct`, but an `enum`
        enum Root: Int {
            case rootFirst, rootSecond, rootThird
        }

        enum Top: Int {
            case topFirst, topSecond, topThird
        }
        case root(Root), top(Top)
    }

    var type: Section?
}

var cb = CustomButton()
cb.type = CustomButton.Section.root(.rootFirst)
cb.type = CustomButton.Section.top(.topSecond)

你的Section结构体根本不是结构体,因为它没有成员 - 它只是一个范围。一旦人们想到它可以包含什么价值,很明显嵌套的枚举就是答案。

答案 1 :(得分:2)

假设定义Section结构的唯一要点是将两个枚举包含在其中,我建议将Section定义为递归枚举。

class CustomButton: UIButton {

    indirect enum Section {
        case number(Int)
        case Root(Section)
        case Top(Section)
    }

    var type: Section?
}

let rootFirstButton = CustomButton()
let rootFirstType = CustomButton.Section.Root(.number(1))
rootFirstButton.type = rootFirstType

let topSecondButton = CustomButton()
topSecondButton.type = CustomButton.Section.Top(.number(2))

请记住,对于这个特定的问题,我可能会使用@ Grimxn的answer,因为没有真正需要枚举的递归,你只需要{{1 }}和Root能够在使用递归方法时获取案例Top的值,甚至是number的值。因此,除非您计划在部分中嵌入部分,否则您不需要递归CustomButton.Section.Root(.Top(.number(3)))

相关问题