gpt4 book ai didi

ios - 需要从父类(super class)属性访问子类属性

转载 作者:行者123 更新时间:2023-11-28 05:44:09 26 4
gpt4 key购买 nike

我需要传递 decodable 类型的模型并从中访问标题和副标题,因为 Decodable 没有标题和副标题属性,所以我实现了 decodable 的扩展,并向 Decodable 添加了标题和副标题属性,所以 Decodable 类型的任何对象可以写 decodableObject.title 所以当我传递符合 decodable 并包含标题和副标题属性的对象时,我需要访问它的数据而不是 Docodable 对象数据但是会发生什么情况它只是访问 Decodable 扩展属性以便访问我的目标对象我应该向下转换到这个类,然后我应该为每个模型类型编写实现

//decalring struct which conforms to Decodable 
struct TestModel:Decodable {
var title:String?
}
//added property
extension Decodable {
var title:String?{
return "Decodable base"
}
}

func setup(){
var testModel = TestModel()
testModel.title = "Subclass"
checkProperties(model: testModel, mod: TestModel.self)
}

func checkProperties<T:Decodable>(model:Any,mod:T.Type){
typealias MMM = T
let title = (model as! MMM).title
print("type is \(title)")
}
// the resutl will be "Type is Decodable Base"

我需要预期的结果//结果将是“类型是子类”

最佳答案

嗯,也许这对你有帮助:

protocol HasTitle {
var title: String? { get }
}

extension Decodable {
var title:String? {
return "Decodable base"
}
}

struct TestModel: Decodable, HasTitle {
var title: String?
}

func checkProperties<T:HasTitle>(model:Any,mod:T.Type){
typealias MMM = T
let title = (model as! MMM).title
print("type is \(title)")
}

编辑

这利用了一个称为追溯建模的概念。基本原理是在协议(protocol)中分离该属性,我称之为 HasTitle。诀窍是对 Decodable 进行扩展,它有一个属性 title 声明的方式与您在 HasTitle 协议(protocol)中期望的方式相同。然后,任何符合 Decodable 的类型都会默认获得 title 属性,您只需声明 HasTitle 一致性。但是,您仍然可以随意覆盖它的 title 属性。

关于ios - 需要从父类(super class)属性访问子类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55559012/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com