0

swift初心者です。

let foo: Encodable

などのEncodableの型を持つ変数をJSONEncoderでエンコードしたいです。
調べたところ、https://forums.swift.org/t/how-to-encode-objects-of-unknown-type/12253
のサイトより、

import Foundation

extension Encodable {
    fileprivate func encode(to container: inout SingleValueEncodingContainer) throws {
        try container.encode(self)
    }
}

struct AnyEncodable1 : Encodable {
    var value: Encodable
    init(_ value: Encodable) {
        self.value = value
    }
    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try value.encode(to: &container)
    }
}

struct MyThing : Encodable {
    let myURL = AnyEncodable1(URL(string: "http://swift.org")!)
}

let url = URL(string: "http://swift.org")
let encoder = JSONEncoder()
var data = try encoder.encode(MyThing())

とするとEncodableの変数もエンコードできることがわかりました。

しかし、このコードだとEncodableAnyEncodable1つにつき1個しか保存できません。

そこで、

extension Encodable {
    fileprivate func encode<K>(to container: inout KeyedEncodingContainer<K>, for key: CodingKey {
        try container.encode(self, forKey: key) 
        // error: Cannot invoke 'encode' with an argument list of type '(Self, forKey: CodingKey)'
    }
}

struct AnyEncodable1 : Encodable {
    var value: Encodable
    init(_ value: Encodable) {
        self.value = value
    }
    enum CodingKeys: String, CodingKey {
        case value
    }
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try value.encode(to: &container, for: .value)
    }
}

struct MyThing : Encodable {
    let myURL = AnyEncodable1(URL(string: "http://swift.org")!)
}

let url = URL(string:  "http://swift.org")
let encoder = JSONEncoder()
var data = try encoder.encode(MyThing())

というようにSingleValueEncodingContainerKeyedEncodingContainerに入れ替えました。しかし、入れ替えると先程までは出ていなかったエラーが出ました。
SingleValueEncodingContainerKeyedEncodingContainerのencodeメソッドの宣言はそれぞれ

// SingleValueEncodingContainer
mutating func encode<T>(_ value: T) throws where T : Encodable
// KeyedEncodingContainer
mutating func encode<T>(_ value: T, forKey key: KeyedEncodingContainer.Key) throws where T : Encodable

KeyedEncodingContainerにはキーが必要だということ以外は変わりません。
しかし、なぜKeyedEncodingContainerではエラーが出るのでしょうか。
ちなみにUnkeyedEncodingContainerに入れ替えるとエラーは出ませんでした。
なぜこのようになるか理由を教えていただけると幸いです。
よろしくお願い致します。
swift4、xcode9.2です。

1 件の回答 1

0

メソッドヘッダの宣言が少し間違えています。() throwsが抜けてまずがそれは置いといて。)


まずは、KeyedEncodingContainer.encode(_:forKey:)の宣言をよくご覧ください。

// KeyedEncodingContainer
mutating func encode<T>(_ value: T, forKey key: KeyedEncodingContainer.Key) throws where T : Encodable

forKeyパラメータの型は任意のCodingKey型ではなく、KeyedEncodingContainer.Key型、つまりそのコンテナのKey型でないといけません。

その定義はこうなっています。

KeyedEncodingContainer.Key

Declaration

typealias KeyedEncodingContainer<K>.Key = K

となっており、要はKeyedEncodingContainerのジェネリック型パラメータKと同じ型を表しています。


あなたのメソッド宣言を見るとこうなっています。

fileprivate func encode<K>(to container: inout KeyedEncodingContainer<K>, for key: CodingKey)

この宣言ですと、パラメータkeyは、containerの型に関係なく、CodingKeyに適合する型ならなんでも良いことになります。これでは先のKeyedEncodingContainer.encode(_:forKey:)メソッドを呼ぶことはできません。

以下のようにkeyの型を書き換えてみてください。

extension Encodable {
    fileprivate func encode<K>(to container: inout KeyedEncodingContainer<K>, for key: K) throws {
        try container.encode(self, forKey: key)
    }
}

これで、keyencode(_:forKey:)の宣言にある制約を満たすことになるので、その部分でのエラーは出なくなるはずです。

1
  • 丁寧なご指摘をありがとうございます。keyの型をKに書き換えたところ、KeyedEncodingContainerでもエンコードすることができました。
    – zinrai4566
    2018年10月9日 12:36

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。