首页 > 解决方案 > How to switch on a RawRepresentable enum type in Swift

问题描述

I have a method that takes type AnyObject and does some magic on it to turn it into a string. However, I cannot get a Swift enum type to work:

    public func magic(on value: AnyObject) {
        var stringVal: String
        switch val {
        case let val as Int:
            stringVal = String(val)
        case let val as RawRepresentable:
            stringVal = val.rawValue
        default:
            assertionFailure("Unhandled type: \(type(of: val))")
            stringVal = val.description
        }

The compiler complains loudly:

I cannot figure out the necessary generic constraint syntax to make the compiler happy.

I also tried this:

        case let val as RawRepresentable where RawValue == String:
            stringVal = val.rawValue

But the compiler complains that RawValue can't be found in scope, even though it is an associatedtype for RawRepresentable.

标签: iosswiftenumsswitch-statementprotocols

解决方案


public func magic<T: AnyObject>(on value: T) where T: RawRepresentable, T: CustomStringConvertible {
    var stringVal: String
    switch value {
    case let val as Int:
        stringVal = String(val)
    case let val where val.rawValue is String:
        stringVal = val.rawValue as! String
    case let val where val.rawValue is Int: // probaly check Int raw values as well
        stringVal = String(val.rawValue as! Int)
    default:
        assertionFailure("Unhandled type: \(type(of: value))")
        stringVal = value.description
    }
    print(stringVal)
}

推荐阅读