代码之家  ›  专栏  ›  技术社区  ›  Benjamin RD

swift-在带参数的枚举中获取大小写和值

  •  0
  • Benjamin RD  · 技术社区  · 7 年前

    我有这个 enum

    public enum Format {
        case label(key: String)
        case textField(key: String)
        case image(key: String)
    }
    

    我可以这样使用它:

    Format.label(key: "abc")

    Format.textField(key: "0.0")

    Format.image(key: "mystringfile")

    当我试图获得价值时,我可以这样做:

    let control = Format.label(key: "abc")
    if case let Format.label(key) = control {
        tmp = key
    } else if case let Format.image(key) = control {
        tmp = key
    } else if case let Format.textField(key) = control {
        tmp = key
    }
    

    有了这个我可以得到价值,但我找不到这个案子 label ,请 textfield image 是的。

    如何找到属于该变量的枚举?

    如果我想用这样的东西: control == Format.label

    我得到了错误:

    二进制运算符“==”不能应用于类型为的操作数 “table.format”和“(string)->格式”

    1 回复  |  直到 7 年前
        1
  •  0
  •   rmaddy    7 年前

    我可能误解了你的问题,但为什么不用 switch 是吗?

    let control = Format.label(key: "abc") // or = Format.textField(key: "whatever") or = Format.image(key: "whatever")
    
    let tmp: String
    switch control {
    case .label(let key):
        // It's a label, do what you need
        tmp = key
    case .textField(let key):
        // It's a textField, do what you need
        tmp = key
    case .image(let key):
        // It's a image, do what you need
        tmp = key
    }
    

    这允许您对类型进行操作并获取值。