I'm trying to put two different generic types into a collection. In this example there are two arrays, one containing Int
s and the other String
s.
let intArray = Array<Int>()
let stringArray = Array<String>()
let dict = [1:intArray, "one": stringArray]
The error reads Type of expression is ambiguous without more context.
So I tried specifying the Dictionary
's type
let dict: [Hashable: Any] = [1:intArray, "one": stringArray]
This leads to two errors.
- Using 'Hashable' as a concrete type conforming to protocol 'Hashable' is not supported.
- Protocol 'Hashable' can only be used as a generic constraint because it has Self or associated type requirements
Adding import Foundation
and using NSDictionary
as the type works fine.
let dict: NSDictionary = [1:intArray, "one": stringArray]
But this should be possible in pure Swift too without using Foundation. What is the type the Dictionary
has to have?
edit: This apparently has more to do with the type of the keys. They have to be of the same type, not just conform to Hashable
.
let dict: [Int:Any] = [1:intArray, 2: stringArray]
This works. But is it possible to make the type of the value more precise? [Int:Array<Any>]
does not work.