0
1

More than 1 year has passed since last update.

Property WrapperとCodableを使ってJSON解析時のデータ型を変換する

Posted at

Property Wrapperとは

プロパティに対して制御を行う仕組み
Swift Language Guide

Codableとは

JSON形式を任意のデータ型に変換するプロトコル
Appleのドキュメント

CodableとProperty Wrapperを連携して使う場面

例えばJSONではStringで定義されたが、実際アプリで使う際はIntになる場合など

Json File

{
"id":"200"
"version":"100" //アプリ側は数値として使いたい
}

Swift Code

struct Hoge: Codable {
    let id: String
    @VersionValue
    let version: Int
}

@propertyWrapper
struct VersionValue: Codable {
    var wrappedValue: Int

    int(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        if let stringValue = try? container.decode(String.self), let intValue = Int(stringValue) {
            wrappedValue = intValue
        } else if let intValue = try? container.decode(Int.self) {
            wrappedValue = intValue
        } else {
            throw DecodingError.dataCorrupdateError(in: container, debugDescripition:"version invalid")
        }
    }
}

0
1
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
1