0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SwiftのCodableとは?初心者向けに簡単に解説してみました!

Posted at

Codableとは?

CodableはSwiftのプロトコルで、
「エンコード(保存用データに変換)」と
「デコード(保存したデータを復元)」をまとめて扱えるようにしたものです。

実はCodableは、

  • Encodable(エンコードできる)

  • Decodable(デコードできる)
    この2つを合わせたものなのです。

つまりCodable = Encodable + Decodableです。

簡単な例(JSONを構造体に変換)

JSON文字列(サーバーからもらうイメージです。)

{
  "name": "Taro",
  "age": 25
}
import Foundation

// ① データモデルをCodableに準拠
struct User: Codable {
    let name: String
    let age: Int
}

// ② JSONデータ(上の文字列をData型に変換)
let json = """
{
    "name": "Taro",
    "age": 25
}
"""

// ③ JSONDecoderでSwiftの構造体に変換
do {
    let user = try JSONDecoder().decode(User.self, from: json)
    print(user.name) // → Taro
    print(user.age)  // → 25
} catch {
    print("変換失敗:", error)
}

👉 JSONDecoder().decode(User.self, from: json)
この1行でJSONをSwiftの構造体にしてくれます。

逆にSwift → JSONに変換(エンコード)

let user = User(name: "Bob", age: 30)

// JSONに変換
do {
    let jsonData = try JSONEncoder().encode(user)
    let jsonString = String(data: jsonData, encoding: .utf8)!
    print(jsonString)
    // → {"name":"Ichiro","age":30}
} catch {
    print("エンコード失敗:", error)
}

まとめ

  • Codableは データ変換(保存・復元)を自動化するプロトコル

  • Encodable + Decodable = Codable

以上、SwiftのCodableの簡単な解説でした、ぜひ参考にしてみてください!🙌

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?