【发布时间】:2018-07-11 23:54:27
【问题描述】:
是否可以为UIColor 实现Encodable 和Decodable 属性
当我尝试添加 Decodable 扩展时,我收到了一个错误
extension UIColor : Decodable {
public required init(from decoder: Decoder) throws {
self.init(red: 1, green: 1, blue: 1, alpha: 1)
}
}
错误:ColorStuff.playground:98:21: 错误:初始化器要求“init(from:)”只能由非最终类“UIColor”定义中的
required初始化器满足 public required init(来自解码器:解码器)抛出 {
我在这里遗漏了什么明显的东西吗?
我对 Encodable 扩展没有任何问题 - 似乎是 Decodable 问题。
错误消息暗示我无法执行此操作,因为无法访问 UIColor 类定义
【问题讨论】:
-
你错过了这个明显的错误:
'required' initializer must be declared directly in class 'UIColor' (not in an extension) -
是的,这就是我所害怕的——正如最后一句话所说。所以我们称之为响亮的 NO WAY JOSE
-
您可以随时尝试subclass 并让子类实现
Codable。或者为它写一个包装器。
标签: ios swift swift4 decodable