【问题标题】:Can I write protocol behave similar to Encodable & Decodable?我可以编写类似于 Encodable 和 Decodable 的协议吗?
【发布时间】:2019-05-07 07:28:40
【问题描述】:

swift4 的Codable 协议非常有用。如果正确定义了构象,它会提供默认的实现函数。

例如这完全没问题:

struct Good: Codable {
    var foo: String // Non-optional
    var bar: Int?  // Optional
}

但这会引发编译错误,要求创建符合协议的协议

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 可以如何改变编码/解码行为?我也可以在我的协议中做类似的事情吗?

【问题讨论】:

  • 规则之类的?不清楚您的意思,例如 UIButton 和 UIView 的“规则”是什么?
  • 可选的还可以,不,不是的。这不是可选的问题,而是协议一致性的问题。 UIButtonUIView 之类的视图本身并不符合 Codable,因为对抽象视图进行编码/解码是没有意义的。
  • Codable 一致性的自动综合需要编译器的支持。所以不,你不能自己做类似的事情(除非你修补编译器)。
  • 我更新了这个问题,让 Joakim 和 vadian 更清楚。谢谢马丁,你可以写一个关于编译器的简短答案,我很乐意接受这个答案。另外,我希望你能解释一下CodingKeys 的工作原理。

标签: swift swift4 swift-protocols codable


【解决方案1】:

Martin 是正确的,您不能在不接触编译器的情况下自行完成此操作。

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

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

struct NotCodableStruct {
    let number: Double
}

此结构不符合 Codable。如果我们把它添加到我们之前的结构中,我们有:

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,因此您无法制定类似的协议。

【讨论】:

  • 虽然您的回答确实扩展了 Martin 的评论,但有关 CodingKeys 的信息仍不清楚它是如何工作的。我可以拥有多个CodingKeys 吗?必须命名为CodingKeysWhateverKeys 可以吗?
  • 协议需要名称CodingKeys。您不能有多个 CodingKeys 每个变量获得一个且只有一个键,并且只有一组 CodingKeys
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-12
  • 2022-01-11
相关资源
最近更新 更多