作为值类型和纯函数的粉丝,我让我所有的模型都是结构体。但是我的一些模型共享我需要进行 JSON 编码的属性。因为我不能使用继承(主要是好的,但在这种情况下不好,但我仍然想坚持使用结构)我需要为每个结构声明这些属性。但是 Swift 的 Codable
不允许
使用 Swift 5.1,是否有任何优雅的解决方案(如避免代码重复和反驳 NSJSONSerialization
和字典黑客)来共享结构的 JSON 键值?尤其是在编码 struct
时。
简单的例子
protocol SerializableModel: Codable {
static var version: Int { get }
static var serializerName: String { get }
}
extension SerializableModel {
// Default value
static var version: Int { 100 }
// Static -> Instance convenience
var version: Int { Self.version }
var serializerName: String { Self.serializerName }
}
enum SharedCodingKeyValues {}
extension SharedCodingKeyValues {
static let version = "version"
static let serializer = "serializer"
}
struct Person {
let name: String
}
extension Person: SerializableModel {
static var serializerName: String = "com.mycompany.person"
}
// MARK: Encodable
extension Person {
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
// Does not even compile: `Cannot invoke 'encode' with an argument list of type '(Int, forKey: String)'`
// try container.encode(version, forKey: SharedCodingKeyValues.version)
// Runtime crash: => `Unexpectedly found nil while unwrapping an Optional value`
// try container.encode(version, forKey: CodingKeys.init(stringValue: SharedCodingKeyValues.version)!)
// try container.encode(serializerName, forKey: CodingKeys.init(stringValue: SharedCodingKeyValues.serializer)!)
}
}
呸!好的,这没有用,目前,我已经屈服于这个我不满意的解决方案:
struct Person {
let name: String
}
extension Person: SerializableModel {
static var serializerName: String = "com.mycompany.person"
}
// MARK: CodingKeys
extension Person {
// Uh, terrible! I REALLY do not wanna do this, because for large models with many stored properties I have to declare ALL my
// JSON keys, even if they are unchanged (waiting for Swift to improve specifically this point)
// Also since just be declaring this, auto-synthesizing of `init(from decoder: Decoder)` stopped working, uhh! This is terrible.
enum CodingKeys: String, CodingKey {
case name
// Does not even compile: `Raw value for enum case must be a literal`
// case serializer = SharedCodingKeyValues.serializer
case serializer // uh, terrible, the name of this enum has to match ALL my other models' CodingKeys.serializer value, and if the JSON key changes server side I need to find and update them all, since I cannot share this value
case version
}
}
// MARK: Encodable
extension Person {
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
try container.encode(version, forKey: .version)
try container.encode(serializerName, forKey: .serializer)
}
}
// MARK: Decodable
extension Person {
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.name = try container.decode(String.self, forKey: .name)
// Actually for now we don't care about any incoming values for the keys `version` and `serializerName` has already been used elsewhere
}
}
这个解决方案有很多不好的地方,请阅读代码内嵌的注释。
我们怎样才能做得更好?
最佳答案
您可以做的是定义一个自定义 CodingKey
它基本上结合了你的模型的编码键和你想要的任何其他编码键,就像这样(警告 - 这里有很多代码,但我做了它所以它足够通用,可以在任何项目中的任何模型中重复使用):
protocol CompoundableCodingKey: CodingKey {
associatedtype OtherCodingKeys1
associatedtype OtherCodingKeys2
init(otherCodingKeys1: OtherCodingKeys1)
init(otherCodingKeys2: OtherCodingKeys2)
init(intValue: Int)
init(stringValue: String)
}
struct CompoundCodingKeys<OtherCodingKeys1: CodingKey, OtherCodingKeys2: CodingKey>: CompoundableCodingKey {
private let otherCodingKeys1: OtherCodingKeys1?
private let otherCodingKeys2: OtherCodingKeys2?
private let internalIntValue: Int?
private let internalStringValue: String
var intValue: Int? {
if let otherCodingKeys1 = otherCodingKeys1 {
return otherCodingKeys1.intValue
} else if let otherCodingKeys2 = otherCodingKeys2 {
return otherCodingKeys2.intValue
}
return internalIntValue
}
var stringValue: String {
if let otherCodingKeys1 = otherCodingKeys1 {
return otherCodingKeys1.stringValue
} else if let otherCodingKeys2 = otherCodingKeys2 {
return otherCodingKeys2.stringValue
}
return internalStringValue
}
init(intValue: Int) {
if let otherCodingKeys1 = OtherCodingKeys1(intValue: intValue) {
self.otherCodingKeys1 = otherCodingKeys1
otherCodingKeys2 = nil
internalIntValue = nil
internalStringValue = otherCodingKeys1.stringValue
} else if let otherCodingKeys2 = OtherCodingKeys2(intValue: intValue) {
otherCodingKeys1 = nil
self.otherCodingKeys2 = otherCodingKeys2
internalIntValue = nil
internalStringValue = otherCodingKeys2.stringValue
} else {
otherCodingKeys1 = nil
otherCodingKeys2 = nil
internalIntValue = intValue
internalStringValue = intValue.description
}
}
init(stringValue: String) {
if let otherCodingKeys1 = OtherCodingKeys1(stringValue: stringValue) {
self.otherCodingKeys1 = otherCodingKeys1
otherCodingKeys2 = nil
internalIntValue = nil
internalStringValue = otherCodingKeys1.stringValue
} else if let otherCodingKeys2 = OtherCodingKeys2(stringValue: stringValue) {
otherCodingKeys1 = nil
self.otherCodingKeys2 = otherCodingKeys2
internalIntValue = nil
internalStringValue = otherCodingKeys2.stringValue
} else {
otherCodingKeys1 = nil
otherCodingKeys2 = nil
internalIntValue = nil
internalStringValue = stringValue
}
}
init(otherCodingKeys1: OtherCodingKeys1) {
self.init(stringValue: otherCodingKeys1.stringValue)
}
init(otherCodingKeys2: OtherCodingKeys2) {
self.init(stringValue: otherCodingKeys2.stringValue)
}
}
extension KeyedEncodingContainerProtocol where Key: CompoundableCodingKey {
mutating func encode<T>(_ value: T, forKey key: Key.OtherCodingKeys1) throws where T: Encodable {
try encode(value, forKey: Key(otherCodingKeys1: key))
}
mutating func encode<T>(_ value: T, forKey key: Key.OtherCodingKeys2) throws where T: Encodable {
try encode(value, forKey: Key(otherCodingKeys2: key))
}
mutating func encodeIfPresent<T>(_ value: T?, forKey key: Key.OtherCodingKeys1) throws where T: Encodable {
try encodeIfPresent(value, forKey: Key(otherCodingKeys1: key))
}
mutating func encodeIfPresent<T>(_ value: T?, forKey key: Key.OtherCodingKeys2) throws where T: Encodable {
try encodeIfPresent(value, forKey: Key(otherCodingKeys2: key))
}
mutating func encodeConditional<T>(_ object: T, forKey key: Key.OtherCodingKeys1) throws where T: AnyObject, T: Encodable {
try encodeConditional(object, forKey: Key(otherCodingKeys1: key))
}
mutating func encodeConditional<T>(_ object: T, forKey key: Key.OtherCodingKeys2) throws where T: AnyObject, T: Encodable {
try encodeConditional(object, forKey: Key(otherCodingKeys2: key))
}
}
extension KeyedEncodingContainerProtocol where Key: CompoundableCodingKey, Key.OtherCodingKeys1: CompoundableCodingKey {
mutating func encode<T>(_ value: T, forKey key: Key.OtherCodingKeys1.OtherCodingKeys1) throws where T: Encodable {
try encode(value, forKey: Key.OtherCodingKeys1(otherCodingKeys1: key))
}
mutating func encode<T>(_ value: T, forKey key: Key.OtherCodingKeys1.OtherCodingKeys2) throws where T: Encodable {
try encode(value, forKey: Key.OtherCodingKeys1(otherCodingKeys2: key))
}
mutating func encodeIfPresent<T>(_ value: T?, forKey key: Key.OtherCodingKeys1.OtherCodingKeys1) throws where T: Encodable {
try encodeIfPresent(value, forKey: Key.OtherCodingKeys1(otherCodingKeys1: key))
}
mutating func encodeIfPresent<T>(_ value: T?, forKey key: Key.OtherCodingKeys1.OtherCodingKeys2) throws where T: Encodable {
try encodeIfPresent(value, forKey: Key.OtherCodingKeys1(otherCodingKeys2: key))
}
mutating func encodeConditional<T>(_ object: T, forKey key: Key.OtherCodingKeys1.OtherCodingKeys1) throws where T: AnyObject, T: Encodable {
try encodeConditional(object, forKey: Key.OtherCodingKeys1(otherCodingKeys1: key))
}
mutating func encodeConditional<T>(_ object: T, forKey key: Key.OtherCodingKeys1.OtherCodingKeys2) throws where T: AnyObject, T: Encodable {
try encodeConditional(object, forKey: Key.OtherCodingKeys1(otherCodingKeys2: key))
}
}
extension KeyedEncodingContainerProtocol where Key: CompoundableCodingKey, Key.OtherCodingKeys2: CompoundableCodingKey {
mutating func encode<T>(_ value: T, forKey key: Key.OtherCodingKeys2.OtherCodingKeys1) throws where T: Encodable {
try encode(value, forKey: Key.OtherCodingKeys2(otherCodingKeys1: key))
}
mutating func encode<T>(_ value: T, forKey key: Key.OtherCodingKeys2.OtherCodingKeys2) throws where T: Encodable {
try encode(value, forKey: Key.OtherCodingKeys2(otherCodingKeys2: key))
}
mutating func encodeIfPresent<T>(_ value: T?, forKey key: Key.OtherCodingKeys2.OtherCodingKeys1) throws where T: Encodable {
try encodeIfPresent(value, forKey: Key.OtherCodingKeys2(otherCodingKeys1: key))
}
mutating func encodeIfPresent<T>(_ value: T?, forKey key: Key.OtherCodingKeys2.OtherCodingKeys2) throws where T: Encodable {
try encodeIfPresent(value, forKey: Key.OtherCodingKeys2(otherCodingKeys2: key))
}
mutating func encodeConditional<T>(_ object: T, forKey key: Key.OtherCodingKeys2.OtherCodingKeys1) throws where T: AnyObject, T: Encodable {
try encodeConditional(object, forKey: Key.OtherCodingKeys2(otherCodingKeys1: key))
}
mutating func encodeConditional<T>(_ object: T, forKey key: Key.OtherCodingKeys2.OtherCodingKeys2) throws where T: AnyObject, T: Encodable {
try encodeConditional(object, forKey: Key.OtherCodingKeys2(otherCodingKeys2: key))
}
}
extension KeyedDecodingContainerProtocol where Key: CompoundableCodingKey {
func decode<T>(_ type: T.Type, forKey key: Key.OtherCodingKeys1) throws -> T where T: Decodable {
try decode(type, forKey: Key(otherCodingKeys1: key))
}
func decode<T>(_ type: T.Type, forKey key: Key.OtherCodingKeys2) throws -> T where T: Decodable {
try decode(type, forKey: Key(otherCodingKeys2: key))
}
func decodeIfPresent<T>(_ type: T.Type, forKey key: Key.OtherCodingKeys1) throws -> T? where T: Decodable {
try decodeIfPresent(type, forKey: Key(otherCodingKeys1: key))
}
func decodeIfPresent<T>(_ type: T.Type, forKey key: Key.OtherCodingKeys2) throws -> T? where T: Decodable {
try decodeIfPresent(type, forKey: Key(otherCodingKeys2: key))
}
}
extension KeyedDecodingContainerProtocol where Key: CompoundableCodingKey, Key.OtherCodingKeys1: CompoundableCodingKey {
func decode<T>(_ type: T.Type, forKey key: Key.OtherCodingKeys1.OtherCodingKeys1) throws -> T where T: Decodable {
try decode(type, forKey: Key.OtherCodingKeys1(otherCodingKeys1: key))
}
func decode<T>(_ type: T.Type, forKey key: Key.OtherCodingKeys1.OtherCodingKeys2) throws -> T where T: Decodable {
try decode(type, forKey: Key.OtherCodingKeys1(otherCodingKeys2: key))
}
func decodeIfPresent<T>(_ type: T.Type, forKey key: Key.OtherCodingKeys1.OtherCodingKeys1) throws -> T? where T: Decodable {
try decodeIfPresent(type, forKey: Key.OtherCodingKeys1(otherCodingKeys1: key))
}
func decodeIfPresent<T>(_ type: T.Type, forKey key: Key.OtherCodingKeys1.OtherCodingKeys2) throws -> T? where T: Decodable {
try decodeIfPresent(type, forKey: Key.OtherCodingKeys1(otherCodingKeys2: key))
}
}
extension KeyedDecodingContainerProtocol where Key: CompoundableCodingKey, Key.OtherCodingKeys2: CompoundableCodingKey {
func decode<T>(_ type: T.Type, forKey key: Key.OtherCodingKeys2.OtherCodingKeys1) throws -> T where T: Decodable {
try decode(type, forKey: Key.OtherCodingKeys2(otherCodingKeys1: key))
}
func decode<T>(_ type: T.Type, forKey key: Key.OtherCodingKeys2.OtherCodingKeys2) throws -> T where T: Decodable {
try decode(type, forKey: Key.OtherCodingKeys2(otherCodingKeys2: key))
}
func decodeIfPresent<T>(_ type: T.Type, forKey key: Key.OtherCodingKeys2.OtherCodingKeys1) throws -> T? where T: Decodable {
try decodeIfPresent(type, forKey: Key.OtherCodingKeys2(otherCodingKeys1: key))
}
func decodeIfPresent<T>(_ type: T.Type, forKey key: Key.OtherCodingKeys2.OtherCodingKeys2) throws -> T? where T: Decodable {
try decodeIfPresent(type, forKey: Key.OtherCodingKeys2(otherCodingKeys2: key))
}
}
然后,如果我们改变SharedCodingKeyValues
进入 CodingKey
枚举,像这样:
enum SharedCodingKeys: String, CodingKey {
case version
case serializer
}
...然后我们可以得到一个以 CompoundCodingKeys<CodingKeys, SharedCodingKeys>
类型为键的容器,它允许您指定 任一个 Person.CodingKeys
(不需要手动定义),或 SharedCodingKeys
,像这样:
// MARK: Encodable
extension Person {
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CompoundCodingKeys<CodingKeys, SharedCodingKeys>.self)
// From `Person.CodingKeys`
try container.encode(name, forKey: .name)
// From `SharedCodingKeys`
try container.encode(version, forKey: .version)
try container.encode(serializerName, forKey: .serializer)
}
}
自 CompoundCodingKeys
本身符合 CodingKey
,您甚至可以更进一步,将任意多的编码键组合成一个,例如 CompoundCodingKeys<CodingKeys, CompoundCodingKeys<SomeOtherCodingKeys, SharedCodingKeys>>
:
enum SomeOtherCodingKeys: String, CodingKey {
case someOtherKey
}
// MARK: Encodable
extension Person {
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CompoundCodingKeys<CodingKeys, CompoundCodingKeys<SomeOtherCodingKeys, SharedCodingKeys>>.self)
// From `Person.CodingKeys`
try container.encode(name, forKey: .name)
// From `SharedCodingKeys`
try container.encode(version, forKey: .version)
try container.encode(serializerName, forKey: .serializer)
// From `SomeOtherCodingKeys`
try container.encode(serializerName, forKey: .someOtherKey)
}
}
关于ios - swift 5 : Non-terrible solutions for sharing of JSON Key-values for Codable Structs?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58630180/