gpt4 book ai didi

swift - 引用可编码协议(protocol)的类不可编码

转载 作者:行者123 更新时间:2023-11-30 10:47:35 33 4
gpt4 key购买 nike

如果我的类 AnotherClass 的成员是具有可编码抽象协议(protocol)的类型,则编译器无法合成该类的编码/解码代码。如果同一个成员是符合相同协议(protocol)的具体类,那么编译器将愉快地合成编码/解码代码。我认为第二种情况应该可行,属性 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()
}
}

最佳答案

这就是解决问题的方法。

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 。它解释了很多关于协议(protocol)行为方式的原因,并将帮助您更多地了解它们。

关于swift - 引用可编码协议(protocol)的类不可编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55442825/

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