例如:
struct type1 {
var t1: String
}
struct type2 {
var t2: Int
}
var dataArray = [type1(t1: "Example"),type2(t2: 2025)]
我可以用类似的事情来完成此操作:
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))]
但是我想知道是否有更好/更轻松/更清洁的方法。
与:
protocol TypeP {
var n: String? { get }
}
struct type1: TypeP {
var t1: String
var n: String?
}
struct type2: TypeP {
var t2: Int
var n: String?
}
enum types {
case one(type1)
case two(type2)
func get() -> ProDateType {
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")}