Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Speaker Deck
PRO
Sign in
Sign up for free
APIクライアントをCodableで置き換えた話
Keisuke Kobayashi
April 19, 2018
Programming
0
1.2k
APIクライアントをCodableで置き換えた話
potatotips #50
Keisuke Kobayashi
April 19, 2018
Tweet
Share
More Decks by Keisuke Kobayashi
See All by Keisuke Kobayashi
今日から始める依存性の注入 / First Time Dependency Injection
kobakei
26
6.3k
iOSアプリの技術的負債をどう返済したか / How to repay the technical debt of iOS app
kobakei
2
760
iOSアプリ内で不正なSSL証明書を検知する / SSL Pinning for iOS apps
kobakei
33
8.4k
Kyashアプリ開発の現場
kobakei
4
2.2k
Review of Google I/O 2017 & Prepare for Google I/O 2018
kobakei
0
260
開発者が知っておきたい通知の歴史
kobakei
10
6.5k
mockito-kotlin
kobakei
1
430
2017年に新規アプリを立ち上げた話
kobakei
2
840
Everything of CI/CD in Kyash Android
kobakei
0
1.3k
Other Decks in Programming
See All in Programming
heyにおけるCI/CDの現状と課題
fufuhu
1
540
"What's new in Swift"の要約 / swift_5_7_summary
uhooi
1
150
Maintaining Software Correctness
dlew
PRO
3
230
Branching out to Jetpack Compose
chrisbanes
4
1.1k
Gitlab CIでMRを自動生成する
forcia_dev_pr
0
110
Value and Record Types
hschwentner
0
540
I/O Extended 2022 in Android ~ Whats new in Android development tools
pluu
0
510
EFFICIENT CREATION OF AN EMPTY COLLECTION IN .NET
abt
0
150
1時間半で克服するJavaScriptの非同期処理/async_javascript_kokufuku
marchin1989
2
590
Custom Design Systems in Compose UI
rharter
5
510
Migrating to Kotlin State & Shared Flows
heyitsmohit
1
180
Running Laravel/PHP on AWS (AWS Builders Day Taiwan 2022)
dwchiang
0
130
Featured
See All Featured
Mobile First: as difficult as doing things right
swwweet
213
7.5k
Debugging Ruby Performance
tmm1
65
10k
Designing for humans not robots
tammielis
241
23k
Intergalactic Javascript Robots from Outer Space
tanoku
261
25k
4 Signs Your Business is Dying
shpigford
169
20k
Raft: Consensus for Rubyists
vanstee
126
5.4k
Fontdeck: Realign not Redesign
paulrobertlloyd
73
4.1k
Documentation Writing (for coders)
carmenhchung
48
2.5k
Product Roadmaps are Hard
iamctodd
34
6.5k
Agile that works and the tools we love
rasmusluckow
319
19k
CSS Pre-Processors: Stylus, Less & Sass
bermonpainter
349
27k
Practical Orchestrator
shlominoach
178
8.6k
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