Can a metatype (.Type) be used as a key in a dictionary?

I have something like this:

class Lumber { } class Fruit { } enum Size { case small case medium case large } let lumberSize = [ Size.small: "2x4", Size.medium: "4x6", Size.large: "6x10" ] let fruitSize = [ Size.small: "grape", Size.medium: "apple", Size.large: "watermelon" ] let size:[AnyObject.Type:Dictionary] = [ Lumber.Type: lumberSize, Fruit.Type: fruitSize ] 

On my definition of the size dictionary, I get this error in real time from the Xcode Editor:

Type 'AnyObject.Type' does not conform to the 'Hashable' protocol

How do I do what I'm trying to do with size ? That is, how to create a dictionary that associates types with dictionaries of a certain size?

I think the ObjectIdentifier will help me, since it is Hashable but I don’t know how to use it, or if it is the right choice.

+9
source share
1 answer

Hashable is a protocol that implements an ObjectIdentifier . This means that ObjectIdentifier(Lumber.Type) is a hashable, not Lumber.Type . You can try changing your code to use an ObjectIdentifier, as in:

 class Lumber { } class Fruit { } enum Size { case small case medium case large } let lumberSize = [ Size.small: "2x4", Size.medium: "4x6", Size.large: "6x10" ] let fruitSize = [ Size.small: "grape", Size.medium: "apple", Size.large: "watermelon" ] let size:[ObjectIdentifier:[Size:String]] = [ ObjectIdentifier(Lumber.self): lumberSize, ObjectIdentifier(Fruit.self): fruitSize ] let t = size[ObjectIdentifier(Lumber.self)] let s = t?[.small] print(s ?? "no s?") 

It compiles and prints "2x4", but I'm not sure if it fits your specific needs. Personally, I would just use the string version of the class name as the key - String(Lumber) . i.e:

 let size:[String:[Size:String]] = [ String(describing:Lumber.self): lumberSize, String(describing:Fruit.self): fruitSize ] let t = size[String(describing:Lumber.self)] let s = t?[.small] print(s ?? "no s?") 
+11
source

Source: https://habr.com/ru/post/1243542/


All Articles