类引用可编码协议不是可编码

时间:2019-03-31 16:09:39

标签: swift encoding decoding swift-protocols

如果我的类AnotherClass的成员是可编码抽象协议类型的,则编译器无法为该类综合编码/解码代码。相反,如果相同成员是遵循相同协议的具体类,则编译器将愉快地合成编码/解码代码。我认为第二种情况应该可行,属性mp始终是MyProtocol的Codable具体实例,即Codable。

/* This works */


protocol MyProtocol : Codable {

    func a(_ n : Int) -> Int

}

class MyClass : MyProtocol {
    let x = 3
    func a( _ n : Int ) -> Int {
        return n * x
    }
}

class AnotherClass : Codable {
    let y = 5
    let mp : MyClass // <---- ACTUAL CLASS
    init() {
        mp = MyClass()
    }
}

/* But this won't work. 
  Compiler error: 
  Type 'AnotherClass' does not conform to protocol 'Decodable'
  Type 'AnotherClass' does not conform to protocol 'Encodable'
*/

protocol MyProtocol : Codable {
    func a(_ n : Int) -> Int
}

class MyClass : MyProtocol {
    let x = 3
    func a( _ n : Int ) -> Int {
        return n * x
    }
}

class AnotherClass : Codable {
    let y = 5
    let mp : MyProtocol // <-------- PROTOCOL
    init() {
        mp = MyClass()
    }
 }

1 个答案:

答案 0 :(得分:0)

这是解决问题的方法。

class AnotherClass<T: MyProtocol> : Codable {
    let y = 5
    let mp : T
    init() {
        mp = MyClass() as! T // handle this more gracefully
    }
}

并以这种方式使用

let a = AnotherClass<MyClass>()

但是请考虑阅读此答案here。它解释了很多协议为什么会以其行为方式运行,并且将帮助您进一步了解它们。