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")
}
}
}