Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
APIクライアントをCodableで置き換えた話
Search
Sponsored
·
Ship Features Fearlessly
Turn features on and off without deploys. Used by thousands of Ruby developers.
→
Keisuke Kobayashi
April 19, 2018
Programming
1.6k
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
APIクライアントをCodableで置き換えた話
potatotips #50
Keisuke Kobayashi
April 19, 2018
More Decks by Keisuke Kobayashi
See All by Keisuke Kobayashi
AI 1st でエンタープライズ SaaS を立ち上げる / AI 1st Enterprise SaaS
kobakei
1
230
プロダクト開発をAI 1stに変革する〜SaaS is dead時代で生き残るために〜 / AI 1st Product Development
kobakei
0
2.7k
今日から始める依存性の注入 / First Time Dependency Injection
kobakei
26
7.7k
iOSアプリの技術的負債をどう返済したか / How to repay the technical debt of iOS app
kobakei
2
1k
iOSアプリ内で不正なSSL証明書を検知する / SSL Pinning for iOS apps
kobakei
34
12k
Kyashアプリ開発の現場
kobakei
4
3k
Review of Google I/O 2017 & Prepare for Google I/O 2018
kobakei
0
350
開発者が知っておきたい通知の歴史
kobakei
9
7.9k
mockito-kotlin
kobakei
1
550
Other Decks in Programming
See All in Programming
JavaDoc 再入門
nagise
0
320
Signal Forms: Beyond the Basics @ngBaguette 2026 in Paris
manfredsteyer
PRO
0
240
3Dシーンの圧縮
fadis
1
730
Skillsは効率化、Agentsは"自分の拡張"——Builder時代のエージェント編成(CC Night 2026)
wemra
1
120
ローカルLLMでどこまでコードが書けるか -拡張版 / How much code can be written on a local LLM Extended
kishida
2
1.2k
Claspは野良GASの夢をみるか
takter00
0
180
A2UI という光を覗いてみる
satohjohn
1
130
フロントエンドとバックエンドで「1文字」を揃えよう
youkidearitai
PRO
0
260
LLM本来の能力を解き放つサンドボックス技術とAI民主化への適用
yukukotani
3
3.6k
AI時代の仕事技芸論 — ソフトウェア開発で「遊ぶように働く」職人的熟達のすすめ
kuranuki
2
660
Spring Security 実践 ─ GraphQL APIで実務に役立つ 認証・認可 を学ぶ
wagyu
0
220
Developing with AI Agents — Codex, Claude Code & Cowork Practical Guide
x5gtrn
PRO
0
1.3k
Featured
See All Featured
The Pragmatic Product Professional
lauravandoore
37
7.3k
The Cult of Friendly URLs
andyhume
79
6.9k
Sam Torres - BigQuery for SEOs
techseoconnect
PRO
0
280
Prompt Engineering for Job Search
mfonobong
0
340
Building an army of robots
kneath
306
46k
The Power of CSS Pseudo Elements
geoffreycrofte
82
6.3k
End of SEO as We Know It (SMX Advanced Version)
ipullrank
3
4.2k
The AI Search Optimization Roadmap by Aleyda Solis
aleyda
1
5.9k
The Success of Rails: Ensuring Growth for the Next 100 Years
eileencodes
47
8.2k
Dealing with People You Can't Stand - Big Design 2015
cassininazir
367
27k
The Mindset for Success: Future Career Progression
greggifford
PRO
0
360
The #1 spot is gone: here's how to win anyway
tamaranovitovic
2
1.1k
Transcript
API クライアントをCodable で 置き換えた話 Keisuke Kobayashi / @kobakei potatotips #50
About Me Keisuke Kobayashi Twitter: @kobakei122 GitHub, Qiita: @Kobakei Kyash,
Inc Android Engineer -> iOS Engineer -> Engineering Manager
会社のブログ Kyash iOS アプリの大規模リファクタリングの話 http://blog.kyash.co/entry/2018/03/20/150238 ちょっとだけバズった
Codable Swift 4 ~ JSON のシリアライズとデシリアライズの仕組み
Sample struct Hoge: Codable { let foo: String let bar:
String? } let data: Data = ... let decoder: JSONDecoder = JSONDecoder() do { let hoge: Hoge = try decoder.decode(Hoge.self, from: data) print(newJson) //Success!!! } catch { ... }
実際のAPI をCodable に置き換 えた
CodableAlamo re https://github.com/Otbivnoe/CodableAlamo re responseDecodableObject が追加される
CodableAlamo re response.result.value で変換後のオブジェクト取得 Alamofire.request(url) .responseDecodableObject { (res: DataResponse<Hoge>) in
let hoge = res.result.value print(hoge) }
enum enum Brand: String, Decodable { case visa = "visa"
case mastercard = "mastercard" }
Nested Object そのまま使える struct Author: Decodable { let name: String
} struct Book: Decodable { let author: Author // 別のDecodable な構造体 }
JSON のキーとstruct のキーが 違う 例) default はSwift の予約語だからisDefault にした い
{ "default": true }
JSON のキーとstruct のキーが 違う CodingKey を作る struct Hoge: Decodable {
let isDefault: Bool private enum CodingKeys: String, CodingKey { case isDefault = "default" } }
日付の文字列をDate に変換す る dateDecodingStrategy にフォーマッタをセット let dateFormatter = DateFormatter() dateFormatter.dateFormat
= "yyyy-MM-dd'T'HH:mm:ss.SSSSSSxxx" dateFormatter.locale = Locale(identifier: "en_US_POSIX") // ↑ これがないと12 時間表記モードでパースできない let decoder = JSONDecoder() decoder.dateDecodingStrategy = .formatted(dateFormatter) let newJson: Hoge = try decoder.decode(Hoge.self, from: data)
JSON とstruct の構造が違う 同じキーでも型が違うJSON (辛い) [ { "type": "user", "target":
{ "firstName": "Keisuke", "lastName": "Kobayashi" } }, { "type": "store", "target": { "name": "Amazon" } } ]
JSON とstruct の構造が違う それぞれのstruct を別のフィールドにする public struct Transaction: Decodable {
let type: String let user: User? let store: Store? private enum CodingKeys: String, CodingKey { case type case target // JSON のキー"target" に対応 } ...
JSON とstruct の構造が違う init を自分で実装する(めんどくさい) decode のキーはいずれもtarget を使う ... public
init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys. type = try values.decode(String.self, forKey: .type) if type == "user" { user = try values.decode(User.self, forKey: .target) } else if type == "store" { store = try values.decode(Store.self, forKey: .target) } } }
まとめ Codable いいぞ Alamo re 使ってるならCodableAlamo re いいぞ つらいJSON でもinit
で自分でデコードすればなん とかなるけどつらいぞ
Try! Codable