需要从超类属性访问子类属性

时间:2019-04-07 12:26:58

标签: ios swift casting codable 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"

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

1 个答案:

答案 0 :(得分:1)

好吧,也许这对您有帮助:

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)")
}

编辑

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

相关问题