2016-12-30 69 views
-1

我怎樣才能迅速建立枚舉從自定義類,像這樣我怎樣才能在斯威夫特

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

的原始類型枚舉的不能是任意類,請參見http://計算器.com/questions/41316815/enum-rawvalue-as-anyclass用於解答類似問題。 –

+0

想一想:'MyType。 Test1 == MyType。 Test1'? –

+0

這不是枚舉的工作方式。但是,您可以使用'static let'而不是'case'來定義它們,並且您可以像這樣訪問它們'MyType.Test1' – EmilioPelaez

回答

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從腦海(解決方法),這不會從類/結構初始化但其具有我的數據

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) } } 

}