如何在Swift中从自定义类创建枚举

时间:2016-12-30 17:16:55

标签: swift enums

如何在自定义类中创建swift中的枚举,如此

class MyClass: NSObject {
    var identifier: String
    var title: String
    var iconName: String

    init(identifier: String, title: String, iconName: String) {
        super.init()
        self.identifier = identifier;
        self.title = title
        self.iconName = iconName
    }
}

示例枚举

enum MyType: MyClass {
        case Test1 = (identifier: "t1", title: "Test 1", iconName: "icn1")
        case Test2 = (identifier: "t2", title: "Test 2", iconName: "icn2")
}

但我有错误not conform to RawRepresentablenot convert to Literal

1 个答案:

答案 0 :(得分:0)

我的解决方案1在网络上找到

enum Devices: CGSize {
   case iPhone3GS = "{320, 480}"
   case iPhone5 = "{320, 568}"
   case iPhone6 = "{375, 667}"
   case iPhone6Plus = "{414, 736}"
}

extension CGSize: StringLiteralConvertible {
    public init(stringLiteral value: String) {
    let size = CGSizeFromString(value)
    self.init(width: size.width, height: size.height)
    }

    public init(extendedGraphemeClusterLiteral value: String) {
    let size = CGSizeFromString(value)
    self.init(width: size.width, height: size.height)
    }

    public init(unicodeScalarLiteral value: String) {
    let size = CGSizeFromString(value)
    self.init(width: size.width, height: size.height)
    }
}

和我的解决方案2(解决方法),这不是来自类/ struct的init,但它有我的数据

typealias MyTypeData = (title: String, iconName: String)
enum MyType: String {
    case Test1
    case Test2

    private var data: MyTypeData {
        switch self {
        case .Test1: return (title: "One", iconName: "icn1")
        case .Test2: return (title: "Two", iconName: "icn2")
        }
    }

    var title: String { get { return data.title } }
    var icon: UIImage? { get { return UIImage(named: data.iconName) } }

}