Enum rawvalue as AnyClass

2019-09-21 18:21发布

问题:

I know you can give enum's the rawvalue of String or Int ect but is there a way to make its type like AnyClass for example

enum Name:AnyClass{
    case classOne = ClassOne
    case classTwo = ClassTwo
}

Where ClassOne and ClassTwo are classes. The error I get is:

Raw type 'AnyClass' is not convertable from any literal

So is there another way to achieve this?

回答1:

So is there another way to achieve this?

I do not know what "this" is, but as far as Swift syntax is concerned, the rule is straightforward. This:

enum Name:AnyClass {

is illegal. Only String and Int are allowed as raw value types (and only String and Int literals are allowed as case values).



回答2:

for example workaround

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

}

or you can try it

enum MyType: String {
     case Test1(data:OneClass)
     case Test2(data:TwoClass)
}