前提
・Xcode Version 9.4.1
・Swift 4
・Jsonの読み込みにCodableを使用
詳細
APIのレスポンスとしてtitle
が返ってきます。
返却値のパターンとしては下記のような2パターンが存在します。
"title": "タイトルだよ!" or "title": {}
①タイトルがString
として格納されているパターン
②タイトルが空のパターンで{}
が返却されるパターン
そこでこれに対応するために下記のようなJson読み込み処理をCodable
を用いて書きました。
struct Hoge: Codable { let title: StringOrEmpty? }
struct Empty: Codable { } enum StringOrEmpty: Codable { case empty(Empty) case string(String) init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if let x = try? container.decode(String.self) { self = .string(x) return } if let x = try? container.decode(Empty.self) { self = .empty(x) return } throw DecodingError.typeMismatch(StringOrEmpty.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for Budget")) } func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() switch self { case .empty(let x): try container.encode(x) case .string(let x): try container.encode(x) } } }
②パターンあるのでcase
でstring
、empty
を作成して対応しました。
わからないこと
タイトルの値を取得できているのですが、値の中身がstring("タイトルだよ!")
というように、case
で指定した形式string(String)
となっています。(当然)
このstring("タイトルだよ!")
の中身、タイトルだよ!
を取り出したいのですがどうすれば良いのでしょうか?
let Hoge = try? JSONDecoder().decode(Hoge.self, from: data) if let title = Hoge.title { print(title) // string("タイトルだよ!") → "タイトルだよ!" 、後者の形にしたい }
ご教示頂けえると幸いです。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。