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
The ROI of Quarkus for Spring Boot Applications
hollycummins
0
150
Contextとはなにか
chiroruxx
1
390
Language Server 使ってる? 〜VSCode と Zed の場合〜 / Are you using a Language Server? ~For VS Code and Zed~
handlename
0
820
分散システム、なんですぐ死んでしまうん?耐障害性を高めたいあなたのためのレジリエンスパターン入門
mshibuya
2
390
20260623_Loop Engineeringで自分の分身の問い合わせBotを作る
ryugen04
0
110
OS アップデート対応の取り組み方がもっと共有されてほしい
andpad
0
110
SREは、MCPとSRE Agentをこう使え!
kazumax55
0
130
【やさしく解説 設計編 #0】DDDのコード、読めるのに分からない人へ
panda728
PRO
1
170
1B+ /day規模のログを管理する技術
broadleaf
0
120
AIを活用したE2Eテスト実装効率化のあゆみ / ebisu-mobile-14-kotetu
kotetuco
0
150
例外の正しい扱い方 そのエラー try-catchして大丈夫?
jinwatanabe
0
320
AIキャラアプリkaiwaの低遅延音声通話基盤をどう作ったか - AWS Gravitonで支える低遅延・低コストAI Agent基盤
mogamit
0
150
Featured
See All Featured
What’s in a name? Adding method to the madness
productmarketing
PRO
24
4.1k
How to Think Like a Performance Engineer
csswizardry
28
2.7k
Bridging the Design Gap: How Collaborative Modelling removes blockers to flow between stakeholders and teams @FastFlow conf
baasie
0
600
Designing Dashboards & Data Visualisations in Web Apps
destraynor
231
55k
Stop Working from a Prison Cell
hatefulcrawdad
274
21k
Efficient Content Optimization with Google Search Console & Apps Script
katarinadahlin
PRO
1
650
Ethics towards AI in product and experience design
skipperchong
2
320
The Pragmatic Product Professional
lauravandoore
37
7.3k
Exploring the Power of Turbo Streams & Action Cable | RailsConf2023
kevinliebholz
37
6.5k
Ruling the World: When Life Gets Gamed
codingconduct
0
270
XXLCSS - How to scale CSS and keep your sanity
sugarenia
250
1.3M
WENDY [Excerpt]
tessaabrams
11
38k
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