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
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
260
プロダクト開発をAI 1stに変革する〜SaaS is dead時代で生き残るために〜 / AI 1st Product Development
kobakei
0
2.8k
今日から始める依存性の注入 / First Time Dependency Injection
kobakei
26
7.8k
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
[2026年度第1回ORセミナー] 計画最適化ベンチャーと競技プログラミング人材
terryu16
0
280
フロントエンドとバックエンドで「1文字」を揃えよう
youkidearitai
PRO
0
780
TAKTでAI駆動開発の品質を設計する
j5ik2o
7
1.6k
Honoでのサプライチェーン侵害対策 〜 3つのライブラリに学ぶ
yusukebe
7
1.7k
SLOをサービス品質の共通言語にするために 取り組んできたこと
wakana0222
0
260
セキュリティの専門家じゃなくてもできる。「セキュリティ意識」をアップデートして サプライチェーン攻撃への耐性を高めよう。
tk3fftk
5
1k
なぜ型を書くのか? TSKaigi2026で改めて考える #tskaigi_smarthr
kajitack
0
180
The Bowling Game- From Imperative to Functional Programming - Part 1
philipschwarz
PRO
0
210
PHPで使える日時の表現と、その知り方 #frontend_phpcon_do
o0h
PRO
0
280
技術的負債解消で開発者の未来を開く- AIの力でコード刷新
kmd2kmd
0
140
吝嗇家のためのAI活用 / AI development for miser - ChatGPT + Issue Driven Development
tooppoo
0
150
OS アップデート対応の取り組み方がもっと共有されてほしい
andpad
0
110
Featured
See All Featured
Measuring & Analyzing Core Web Vitals
bluesmoon
9
870
Code Reviewing Like a Champion
maltzj
528
40k
Claude Code のすすめ
schroneko
67
230k
What’s in a name? Adding method to the madness
productmarketing
PRO
24
4.1k
Bioeconomy Workshop: Dr. Julius Ecuru, Opportunities for a Bioeconomy in West Africa
akademiya2063
PRO
1
170
Responsive Adventures: Dirty Tricks From The Dark Corners of Front-End
smashingmag
254
22k
Measuring Dark Social's Impact On Conversion and Attribution
stephenakadiri
2
230
Darren the Foodie - Storyboard
khoart
PRO
3
3.4k
Why Mistakes Are the Best Teachers: Turning Failure into a Pathway for Growth
auna
0
180
30 Presentation Tips
portentint
PRO
1
340
Build your cross-platform service in a week with App Engine
jlugia
234
18k
[Rails World 2023 - Day 1 Closing Keynote] - The Magic of Rails
eileencodes
38
2.9k
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