Article

Encoding and Decoding Custom Types あつらえの型のエンコーディングとデコーディング

Make your data types encodable and decodable for compatibility with external representations such as JSON. あなたのデータ型のエンコーディングとデコーディングを外部表現、例えばJSONなどとの互換性のために行います。

Overview 概要

Many programming tasks involve sending data over a network connection, saving data to disk, or submitting data to APIs and services. These tasks often require data to be encoded and decoded to and from an intermediate format while the data is being transferred. 多くのプログラミング作業がネットワーク接続を越えてのデータの送信、ディスク上でのデータの保存、またはAPIおよびサービスへのデータの提出を伴います。これらの作業がしばしばデータに要求するのは、データが転送される間に中間形式へとおよびそれからエンコードおよびデコードされることです。

The Swift standard library defines a standardized approach to data encoding and decoding. You adopt this approach by implementing the Encodable and Decodable protocols on your custom types. Adopting these protocols lets implementations of the Encoder and Decoder protocols take your data and encode or decode it to and from an external representation such as JSON or property list. To support both encoding and decoding, declare conformance to Codable, which combines the Encodable and Decodable protocols. This process is known as making your types codable. Swift標準ライブラリは、標準化された取り組みをデータのエンコードとデコードに対して定義します。あなたはこの取り組みをEncodableDecodableプロトコルをあなたのあつらえの型で実装することで採用します。これらのプロトコルの採用は、EncoderDecoderプロトコルの実装に、あなたのデータを取らせて、それをJSONやプロパティリストのような外部表現へとそしてそれからエンコードおよびデコードさせます。エンコードとデコードの両方をサポートするには、Codableへの準拠を宣言してください、それはEncodableDecodableプロトコルを一体化します。この過程は、あなたの型をコード化可能にするとして知られています。

Encode and Decode Automatically 自動的にエンコードおよびデコードする

The simplest way to make a type codable is to declare its properties using types that are already Codable. These types include standard library types like String, Int, and Double; and Foundation types like Date, Data, and URL. Any type whose properties are codable automatically conforms to Codable just by declaring that conformance. ある型をコード化可能にするもっとも単純な方法は、既にCodableである型のどれかを使ってそれのプロパティを宣言することになります。それらの型は、StringInt、そしてDoubleのような標準ライブラリ;そしてDateData、そしてURLのようなFoundation型を含みます。それらのプロパティがコード化可能なあらゆる型は、単にその準拠を宣言することによって自動的にCodableに準拠します。

Consider a Landmark structure that stores the name and founding year of a landmark: 歴史的建築物の名前と建造年を格納するLandmark構造体を考えてください:


struct Landmark {
    var name: String
    var foundingYear: Int
}

Adding Codable to the inheritance list for Landmark triggers an automatic conformance that satisfies all of the protocol requirements from Encodable and Decodable: CodableLandmarkに対する継承リストに加えることは、EncodableDecodableからのプロトコル要件のすべてを満たす自動的準拠を引き起こします。


struct Landmark: Codable {
    var name: String
    var foundingYear: Int
    
    // Landmark now supports the Codable methods init(from:) and encode(to:), 
    // even though they aren't written as part of its declaration.
}

Adopting Codable on your own types enables you to serialize them to and from any of the built-in data formats, and any formats provided by custom encoders and decoders. For example, the Landmark structure can be encoded using both the PropertyListEncoder and JSONEncoder classes, even though Landmark itself contains no code to specifically handle property lists or JSON. Codableをいろいろなあなた独自の型で採用することは、あなたにそれらをあらゆる組込みデータ形式、そしてあつらえのエンコーダとデコーダによって提供されるあらゆる形式へとおよびそれからシリアライズすることを可能にします。例えば、Landmark構造体は、PropertyListEncoderJSONEncoderクラスの両方を使ってエンコードされます、Landmarkそれ自身がプロパティリストまたはJSONを具体的に取り扱うコードを含まないとしてもです。

The same principle applies to custom types made up of other custom types that are codable. As long as all of its properties are Codable, any custom type can also be Codable. 同じ原理は、コード化可能である他のあつらえの型から成り立っているあつらえの型に適用されます。それのプロパティの全てがCodableである限り、あらゆるあつらえの型もまたCodableです。

The example below shows how automatic Codable conformance applies when a location property is added to the Landmark structure: 下の例は、自動的にCodable準拠を、locationプロパティがLandmark構造体に加えられる時に適用する方法を示します:


struct Coordinate: Codable {
    var latitude: Double
    var longitude: Double
}


struct Landmark: Codable {
    // Double, String, and Int all conform to Codable.
    var name: String
    var foundingYear: Int
    
    // Adding a property of a custom Codable type maintains overall Codable conformance.
    var location: Coordinate
}

Built-in types such as Array, Dictionary, and Optional also conform to Codable whenever they contain codable types. You can add an array of Coordinate instances to Landmark, and the entire structure will still satisfy Codable. 組込みの型、例えばArrayDictionary、そしてOptionalもまた、それらがコード化可能な型を含む時はいつでもCodableに準拠します。あなたはCoordinateインスタンスからなる配列をLandmarkに追加できます、そして構造体全体は依然としてCodableを満たします。

The example below shows how automatic conformance still applies when adding multiple properties using built-in codable types within Landmark: 下の例は、どのように自動的な準拠が依然として適用されるか、複数のプロパティを組込みのコード化可能型を使ってLandmark構造体内部に加える場合に示します:


struct Landmark: Codable {
    var name: String
    var foundingYear: Int
    var location: Coordinate
    
    // Landmark is still codable after adding these properties.
    var vantagePoints: [Coordinate]
    var metadata: [String: String]
    var website: URL?
}

Encode or Decode Exclusively 排他的にエンコードおよびデコードする

In some cases, you may not need Codable's support for bidirectional encoding and decoding. For example, some apps only need to make calls to a remote network API and do not need to decode a response containing the same type. Declare conformance to Encodable if you only need to support the encoding of data. Conversely, declare conformance to Decodable if you only need to read data of a given type. いくつかの場合には、あなたはCodableのもつ双方向のエンコーディングとデコーディングに対する支援を必要としないかもしれません。例えば、いくつかのアプリはリモートネットワークAPIへの呼び出しだけを必要として、同じ型を含んでいる返答をデコードする必要がありません。Encodableへの準拠を、あなたがデータのエンコーディングの支援のみを必要とするならば宣言してください。反対に、Decodableへの準拠を、あなたが与えられた型のデータを読み込みのみを必要とするならば宣言してください。

The examples below show alternative declarations of the Landmark structure that only encode or decode data: 下の例は、Landmark構造体でデータのエンコードまたはデコードのみを行う選択的な宣言を示します:


struct Landmark: Encodable {
    var name: String
    var foundingYear: Int
}

struct Landmark: Decodable {
    var name: String
    var foundingYear: Int
}

Choose Properties to Encode and Decode Using Coding Keys プロパティを選択してエンコードとデコードをコーディングキーを使って行う

Codable types can declare a special nested enumeration named CodingKeys that conforms to the CodingKey protocol. When this enumeration is present, its cases serve as the authoritative list of properties that must be included when instances of a codable type are encoded or decoded. The names of the enumeration cases should match the names you've given to the corresponding properties in your type. コード化可能型は、CodingKeysと名前を付けられ、CodingKeyプロトコルに準拠する、ある特殊な入れ子列挙を宣言できます。この列挙が存在する時、それのケース節は、コード化可能型のインスタンスがエンコードまたはデコードされる時に含められる必要があるプロパティの正式リストとしての機能を果たします。これら列挙ケース節の名前は、あなたの型の中の対応するプロパティにあなたが与えた名前と合致しなければなりません。

Omit properties from the CodingKeys enumeration if they won't be present when decoding instances, or if certain properties shouldn't be included in an encoded representation. A property omitted from CodingKeys needs a default value in order for its containing type to receive automatic conformance to Decodable or Codable. これらプロパティをCodingKeys列挙から省略してください、もしそれらがインスタンスをデコードする時に存在しないならば、または若干のプロパティがエンコード済み表現の中に含められるべきでないならば。CodingKeysから省略されたあるプロパティは、それの容れ物である型がDecodableまたはCodableへの自動的な準拠を受け取るために初期状態の値が必要です。

If the keys used in your serialized data format don't match the property names from your data type, provide alternative keys by specifying String as the raw-value type for the CodingKeys enumeration. The string you use as a raw value for each enumeration case is the key name used during encoding and decoding. The association between the case name and its raw value lets you name your data structures according to the Swift API Design Guidelines rather than having to match the names, punctuation, and capitalization of the serialization format you're modeling. あなたの特殊化されたデータ型において使われるキーがあなたのデータ型からのプロパティ名と一致しないならば、代替のキーの提供をStringCodingKeys列挙に対する生の値型として指定することによって行ってください。あなたが各列挙節に対して生の値として使う文字列は、エンコーディングおよびデコーディングの間に使うキー名です。ケース節名とそれの生の値の間の関連性は、あなたにSwift API Design Guidelinesに従ってあなたのデータ構造体に名前を付けさせます、あなたがモデリングしているシリアライズ形式での名前、句読点、そして大文字の使い方に合わせるのではなく。

The example below uses alternative keys for the name and foundingYear properties of the Landmark structure when encoding and decoding: 下の例は、代替キーの使用を、Landmark構造体のnamefoundingYearプロパティに対して、エンコードおよびデコードする時に行います。


struct Landmark: Codable {
    var name: String
    var foundingYear: Int
    var location: Coordinate
    var vantagePoints: [Coordinate]
    
    enum CodingKeys: String, CodingKey {
        case name = "title"
        case foundingYear = "founding_date"
        
        case location
        case vantagePoints
    }
}

Encode and Decode Manually 手動でエンコードおよびデコードする

If the structure of your Swift type differs from the structure of its encoded form, you can provide a custom implementation of Encodable and Decodable to define your own encoding and decoding logic. あなたのSwift型の構造体がそれのエンコード形式の構造体と異なるならば、あなたはEncodableおよびDecodableのあつらえの実装を提供することであなた独自のエンコードおよびデコード論理を定義できます。

In the examples below, the Coordinate structure is expanded to support an elevation property that's nested inside of an additionalInfo container: 下の例において、Coordinate構造体は拡張されることでelevationプロパティをサポートします、それはadditionalInfoコンテナの内部に入れ子にされます:


struct Coordinate {
    var latitude: Double
    var longitude: Double
    var elevation: Double


    enum CodingKeys: String, CodingKey {
        case latitude
        case longitude
        case additionalInfo
    }
    
    enum AdditionalInfoKeys: String, CodingKey {
        case elevation
    }
}

Because the encoded form of the Coordinate type contains a second level of nested information, the type's adoption of the Encodable and Decodable protocols uses two enumerations that each list the complete set of coding keys used on a particular level. Coordinate型のエンコード形式は入れ子にされた情報の2番目の水準を含むことから、その型のもつEncodableDecodableプロトコルの採用は2つの列挙を使います、それはそれぞれが特定の水準で使われるコーディングキーの完全な一揃いを列記します。

In the example below, the Coordinate structure is extended to conform to the Decodable protocol by implementing its required initializer, init(from:): 下の例において、Coordinate構造体は拡張されて、Decodableプロトコルにそれの必須イニシャライザ、init(from:)を実装することで準拠します:


extension Coordinate: Decodable {
    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        latitude = try values.decode(Double.self, forKey: .latitude)
        longitude = try values.decode(Double.self, forKey: .longitude)
        
        let additionalInfo = try values.nestedContainer(keyedBy: AdditionalInfoKeys.self, forKey: .additionalInfo)
        elevation = try additionalInfo.decode(Double.self, forKey: .elevation)
    }
}

The initializer populates a Coordinate instance by using methods on the Decoder instance it receives as a parameter. The Coordinate instance's two properties are initialized using the keyed container APIs provided by the Swift standard library. このイニシャライザは、それがパラメータとして受け取るDecoderインスタンス上でメソッドを使うことでCoordinateインスタンスを満たします。Coordinateインスタンスのもつ2つのプロパティは、Swift標準ライブラリによって提供されるキー付きコンテナAPIを使って初期化されます。

The example below shows how the Coordinate structure can be extended to conform to the Encodable protocol by implementing its required method, encode(to:): 下の例は、どのようにCoordinate構造体が拡張されて、Encodableプロトコルにそれの必須メソッドencode(to:)を実装することで準拠するかを示します:


extension Coordinate: Encodable {
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(latitude, forKey: .latitude)
        try container.encode(longitude, forKey: .longitude)
        
        var additionalInfo = container.nestedContainer(keyedBy: AdditionalInfoKeys.self, forKey: .additionalInfo)
        try additionalInfo.encode(elevation, forKey: .elevation)
    }
}

This implementation of the encode(to:) method reverses the decoding operation from the previous example. encode(to:)メソッドのこの実装は、デコーディング演算を前の例から入れ替えます。

For more information about the container types used when customizing the encoding and decoding process, see KeyedEncodingContainerProtocol and UnkeyedEncodingContainer. デコーディングとエンコーディング過程をカスタマイズする時に使われるコンテナ型についての詳細は、KeyedEncodingContainerProtocolUnkeyedEncodingContainerを見てください。

See Also 参照

Adopting Codability

Related Documentation 関連文書