2

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

quanguyen
  • 1,443
  • 3
  • 17
  • 29
  • 1
    This is a known bug: https://bugs.swift.org/browse/SR-7049 – Hamish Jun 19 '18 at 09:29
  • You should define your own `protocol` instead of using `AnyHashable`. `protocol WeekDayOrInt` `extension WeekDay: WeekDayOrInt { }` `extension Int: WeekDayOrInt { }` `var dict = [WeekDayOrInt : [Int]]()`. Then those two types and only those two types can be used as keys for your dict. – vacawama Jun 19 '18 at 09:51

1 Answers1

7

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)")
}
Kamran
  • 14,987
  • 4
  • 33
  • 51