Reputation: 21304
Is it possible to define dictionray with two types possible for values? Something like:
var obj = [String: String, Int]()
Upvotes: 0
Views: 111
Reputation: 63167
You can extend all the types you need with a protocol, and the value have that protocol type:
protocol StringOrInt {};
extension String: StringOrInt {}
extension Int: StringOrInt {}
let dict = [String: StringOrInt]()
Using an enumeration might be better, though, such as:
enum StringOrInt {
case string(String)
case int(Int)
}
let obj: [ String : StringOrInt] = [
"a": .string("Hello"),
"b": .int(42)
]
Upvotes: 3