當資料來源的格式有異動時,可以利用 protocol + associatedtype + extension (如果摸不到 struct 尤其需要,摸得到可以在 struct 內繼承,也還是可以用 extension)
去做深層的 protocol
用來達成透過 protocol 取值,不用判斷 source 為何~
protocol Vendor {
var venderId: Any { get }
associatedtype BrandType: Brand
var brands: [BrandType] { get }
}
protocol Brand {
var name: String { get }
}
extension BrandA: Brand{}
extension BrandB: Brand{}
extension VenderA: Vendor {
var venderId: Any { self.id }
typealias BrandType = BrandA
}
extension VenderB: Vendor {
var venderId: Any { return self.id }
typealias BrandType = BrandB
}
func processVendor<T: Vendor>(_ vendor: T) {
print("Processing vendor with id: \(vendor.venderId)")
for brand in vendor.brands {
print("Brand name: \(brand.name)")
}
}