Search code examples
swiftenumscastingoption-typeunwrap

swift cast from AnyHashable to enum


I have this playground:

import Foundation

enum WeekDay: Int {
    case mon, tues, wed, thurs, fri, sat, sun
}

let wd = WeekDay(rawValue: 0)! // mon

let param = [wd: [1, 2, 3]]
message(dict: param)

func message(dict: [AnyHashable: [Int]?]) {
    for (k, v) in dict {
        print(k, type(of: k), v) // mon AnyHashable Optional([1, 2, 3])

        if let k = k as? WeekDay {
            print("got it: \(k)")
        }
    }
}

But I can never get got it: ... printed.

Why can't I cast from an AnyHashable to WeekDay?

The reason I want to use AnyHashable in function message is that the key of dict can be Int or WeekDay. If I don't use AnyHashable, what type should I use for my purpose?

Thanks


Solution

  • You should use the base value of AnyHashable to cast back to its original type as below,

    if let k = (k.base as? WeekDay), k == .mon {
       print("got it: \(k)")
    }