Kosmetika
Kosmetika

Reputation: 21304

Swift 3 - Define dictionary with possible two types

Is it possible to define dictionray with two types possible for values? Something like:

var obj = [String: String, Int]()

Upvotes: 0

Views: 111

Answers (2)

Alexander
Alexander

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

Use Any : var someObject : [String:Any] = [:]

Upvotes: 0

Related Questions