首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我可以编写类似于Encodable & Decodable的协议行为吗?

我可以编写类似于Encodable & Decodable的协议行为吗?
EN

Stack Overflow用户
提问于 2019-05-07 15:28:40
回答 1查看 148关注 0票数 0

Swift4的Codable协议非常有用。如果正确定义了一致性,它将提供默认的实现函数。

例如,这完全没问题:

代码语言:javascript
复制
struct Good: Codable {
    var foo: String // Non-optional
    var bar: Int?  // Optional
}

但这将引发编译错误,并请求创建符合协议的

代码语言:javascript
复制
struct Bad: Codable {
   var foo: UIButton // Non-optional raise compile error for not conforming Codable Protocol
   var bar: UIView? // optional is okay (not compile error because when decode failed, it fallback to nil)
   var codable: SomeCodable // if the property is also Codable, then it's fine too!
}

因此,问题是:我是否可以编写一个协议,要求其符合自身(就像属性需要符合同一协议一样)?

如果是,是如何实现的?若否,原因何在?

另外,我还想知道在结构中定义CodingKeys会如何改变编码/解码行为?我可以在我的协议中做类似的事情吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-07 19:12:33

Martin是正确的,你不能在不接触编译器的情况下自己做这件事。

首先,让我们看一下这个基本的示例,其中我解释了如何使用编码键。

代码语言:javascript
复制
struct CodableStruct: Codable {
let primitive: Int // No issues yet

enum CodingKeys: String, CodingKey {
    case primitive
    // This is the default coding key (i.e the JSON has structure ["primitive": 37]
    // You can change this key to anything you need
    //
    // ex case primitive = "any_thing_you_want"
    // JSON has to have structure ["any_thing_you_want": 37]
}

}

更改codingKey只会更改代码在从JSON中“解码”该值时将使用的键。

现在让我们来谈谈编译器。假设我们创建另一个struct

代码语言:javascript
复制
struct NotCodableStruct {
    let number: Double
}

此结构不符合Codable。如果我们把这段代码添加到前面的结构中,我们会得到:

代码语言:javascript
复制
struct CodableStruct: Codable {
    let primative: Int
    let notCodable: NotCodableStruct // doesn't compile because this doesn't conform to codable

    enum CodingKeys: String, CodingKey {
        case primative
        case notCodable
    }
}

由于NotCodableStruct不符合Codable,编译器抱怨道。换句话说,符合Codable的结构或对象中的所有变量也必须符合Codable。有关更多信息,请参见以下屏幕截图。

当然,如果您让NotCodableStruct符合Codable,每个人都会再次高兴起来。由于您无法强制要求所有变量都符合Codable,因此您无法制定类似的协议。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56017574

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档