I would like to know if I can have a Swift array or dictionary with multiple types.
For example:
struct type1 {
var t1: String
}
struct type2 {
var t2: Int
}
var dataArray = [type1(t1: "Example"),type2(t2: 2025)]
I can accomplish this with something like:
struct arrayType {
var t1: type1?
var t2: type2?
//to get the type
var type: String
init(t1: type1? = nil, t2: type2? = nil) {
self.t1 = t1
self.t2 = t2
self.type = { if t1 != nil {
"type1"
} else if t2 != nil {
"type2"
} else {
"unset"
}}()
}
}
var dataArray = [arrayType(t1: type1(t1: "Example")),arrayType(t2: type2(t2: 2025))]
but I was wondering if there is a better/easier/cleaner way to do it.
Using a enum like this works:
import Foundation
protocol TypeP {
var type: String { get set }
}
struct type1: TypeP {
var t1: String
var type = "T1"
}
struct type2: TypeP {
var t2: Int
var type = "T2"
}
enum types {
case one(type1)
case two(type2)
func get() -> TypeP {
switch self {
case .one(let t1):
return t1
case .two(let t2):
return t2
}
}
}
var data = [types.one(type1(t1: "Example")),types.two(type2(t2: 2025)),types.one(type1(t1: "Example"))]
//to show it works
if type(of: data[2].get()) == type1.self {print(data[2].get().self as! type1)} else {print("non")}
Also, https://app.quicktype.io/ can help generate code to parse JSON when your stuck.