具有符合 Swift 中 Encodable 通用属性的结构体

Flo*_*n_L 5 generics struct type-erasure swift encodable

我一直在寻找一种在结构中具有通用属性的方法,其中类型在运行时定义,例如:

struct Dog {
    let id: String
    let value: ??
}
Run Code Online (Sandbox Code Playgroud)

一个有用的简单用例是构建对象时json。Anode可以是intstringbool、数组等,但除了类型可以改变之外,对象node保持不变。

经过一番思考并使用失败protocols(出现常见protocol 'X' can only be used as a generic constraint because it has Self or associated type requirements错误)后,我想出了两种不同的解决方案,#0 使用type erasure和 #1 使用type-erasureand generics

#0(类型擦除)

struct AnyDog: Encodable {

    enum ValueType: Encodable {
        case int(Int)
        case string(String)

        func encode(to encoder: Encoder) throws {
            var container = encoder.singleValueContainer()
            switch self {
            case .int(let value):
                try container.encode(value)
            case .string(let value):
                try container.encode(value)
            }
        }
    }

    let id: String
    let value: ValueType

    init(_ dog: DogString) {
        self.id = dog.id
        self.value = .string(dog.value)
    }

    init(_ dog: DogInt) {
        self.id = dog.id
        self.value = .int(dog.value)
    }
}

struct DogString: Encodable{
    let id: String
    let value: String

    var toAny: AnyDog {
        return AnyDog(self)
    }
}

struct DogInt: Encodable {
    let id: String
    let value: Int

    var toAny: AnyDog {
        return AnyDog(self)
    }
}

let dogs: [AnyDog] = [
    DogString(id: "123", value: "pop").toAny,
    DogInt(id: "123", value: 123).toAny,
]

do {
    let data = try JSONEncoder().encode(dogs)
    print(String(data: data, encoding: .utf8)!)
} catch {
    print(error)
} 
Run Code Online (Sandbox Code Playgroud)

#1(类型擦除+泛型)

struct AnyDog: Encodable {

    enum ValueType: Encodable {
        case int(Int)
        case string(String)

        func encode(to encoder: Encoder) throws {
            var container = encoder.singleValueContainer()
            switch self {
            case .int(let value):
                try container.encode(value)
            case .string(let value):
                try container.encode(value)
            }
        }
    }

    let id: String
    let value: ValueType
}

struct Dog<T: Encodable>: Encodable{
    let id: String
    let value: T

    var toAny: AnyDog {
        switch T.self {
        case is String.Type:
            return AnyDog(id: id, value: .string(value as! String))
        case is Int.Type:
            return AnyDog(id: id, value: .int(value as! Int))
        default:
            preconditionFailure("Invalid Type")
        }
    }
}
let dogs: [AnyDog] = [
    Dog<String>(id: "123", value: "pop").toAny ,
    Dog<Int>(id: "123", value: 123).toAny,
]

do {
    let data = try JSONEncoder().encode(dogs)
    print(String(data: data, encoding: .utf8)!)
} catch {
    print(error)
}
Run Code Online (Sandbox Code Playgroud)

两种方法都会给出适当的结果:

[{"id":"123","value":"pop"},{"id":"123","value":123}]
Run Code Online (Sandbox Code Playgroud)

即使结果相同,我坚信scalable如果考虑更多类型,方法 #1 更有效,但对于添加的每种类型,仍然需要在 2 个不同区域进行更改。

我确信有更好的方法来实现这一目标,但尚未找到。很高兴听到任何有关它的想法或建议。


编辑 #0 2020/02/08:可选值

使用罗布的精彩答案,我现在尝试允许value像这样可选:

[{"id":"123","value":"pop"},{"id":"123","value":123}]
Run Code Online (Sandbox Code Playgroud)

此时,T无法再推断并抛出以下错误:

generic parameter 'T' could not be inferred
Run Code Online (Sandbox Code Playgroud)

我正在寻找使用 Rob 的答案的可能性,如果给出以下Optional结果value

[{"id":"123","value":123},{"id":"456","value":null}]
Run Code Online (Sandbox Code Playgroud)

编辑 #1 2020/02/08:解决方案

好吧,我是如此专注于给出valuenil,以至于我没有意识到nil没有任何类型会导致推理错误。

提供一个可选类型使其起作用:

struct Dog: Encodable {
    // This is the key to the solution: bury the type of value inside a closure
    let valueEncoder: (Encoder) throws -> Void

    init<T: Encodable>(id: String, value: T?) {
        self.valueEncoder = {
            var container = $0.container(keyedBy: CodingKeys.self)
            try container.encode(id, forKey: .id)
            try container.encode(value, forKey: .value)
        }
    }

    enum CodingKeys: String, CodingKey {
        case id, value
    }

    func encode(to encoder: Encoder) throws {
        try valueEncoder(encoder)
    }
}

let dogs = [
    Dog(id: "123", value: 123),
    Dog(id: "456", value: nil),
]

do {
    let data = try JSONEncoder().encode(dogs)
    print(String(data: data, encoding: .utf8)!)
} catch {
    print(error)
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*ier 5

如果您所描述的确实是您想要的,则无需任何这些类型的橡皮擦即可完成。您所需要的只是一个关闭。(但这假设Dog确实仅存在用于编码,正如您所描述的,并且value除此之外没有任何需要。)

struct Dog: Encodable {
    // This is the key to the solution: bury the type of value inside a closure
    let valueEncoder: (Encoder) throws -> Void

    init<T: Encodable>(id: String, value: T) {
        self.valueEncoder = {
            var container = $0.container(keyedBy: CodingKeys.self)
            try container.encode(id, forKey: .id)
            try container.encode(value, forKey: .value)
        }
    }

    enum CodingKeys: String, CodingKey {
        case id, value
    }

    func encode(to encoder: Encoder) throws {
        try valueEncoder(encoder)
    }
}
Run Code Online (Sandbox Code Playgroud)

由于value只在 内部使用过valueEncoder,所以世界其他地方不需要知道它的类型(Dog 甚至不需要知道它的类型)。这就是类型擦除的全部内容。它不需要创建额外的包装类型或通用结构。

如果您想保留诸如DogString和 之类的类型DogInt,您也可以通过添加协议来实现:

protocol Dog: Encodable {
    associatedtype Value: Encodable
    var id: String { get }
    var value: Value { get }
}
Run Code Online (Sandbox Code Playgroud)

然后创建一个 DogEncoder 来处理编码(与上面相同,除了一个新的 init 方法):

struct DogEncoder: Encodable {
    let valueEncoder: (Encoder) throws -> Void

    init<D: Dog>(_ dog: D) {
        self.valueEncoder = {
            var container = $0.container(keyedBy: CodingKeys.self)
            try container.encode(dog.id, forKey: .id)
            try container.encode(dog.value, forKey: .value)
        }
    }

    enum CodingKeys: String, CodingKey {
        case id, value
    }

    func encode(to encoder: Encoder) throws {
        try valueEncoder(encoder)
    }
}
Run Code Online (Sandbox Code Playgroud)

几种狗:

struct DogString: Dog {
    let id: String
    let value: String
}

struct DogInt: Dog  {
    let id: String
    let value: Int
}
Run Code Online (Sandbox Code Playgroud)

将它们放入编码器数组中:

let dogs = [
    DogEncoder(DogString(id: "123", value: "pop")),
    DogEncoder(DogInt(id: "123", value: 123)),
]

let data = try JSONEncoder().encode(dogs)
Run Code Online (Sandbox Code Playgroud)