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
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
The NotImplementedError Problem in Ruby
koic
1
660
ユニットテストの先へ:テスト技法で要求・仕様を整理するJava開発実践 / Beyond_Unit_Testing_Practical_Java_Development_Techniques_for_Organizing_Requirements_and_Specifications
shimashima35
0
380
jQueryをバージョンアップする前に使いたいjQuery Migrate
matsuo_atsushi
0
200
過去最大のMCPアップデート! 2026-07-28 RC版の謎に迫る
licux
6
190
LLM本来の能力を解き放つサンドボックス技術とAI民主化への適用
yukukotani
3
3.4k
AI時代のUIはどこへ行く?その2!
yusukebe
19
6.9k
生成AI時代にこそ効くGo | Why Go Works in the Age of Generative AI
mom0tomo
8
3.2k
dRuby over BLE
makicamel
2
330
AutonomyとControlのあいだ:Graflowで記述するAIエージェント協調
myui
0
110
Claspは野良GASの夢をみるか
takter00
0
180
Spring Security 実践 ─ GraphQL APIで実務に役立つ 認証・認可 を学ぶ
wagyu
0
210
3Dシーンの圧縮
fadis
1
680
Featured
See All Featured
Ethics towards AI in product and experience design
skipperchong
2
300
What Being in a Rock Band Can Teach Us About Real World SEO
427marketing
0
250
A better future with KSS
kneath
240
18k
What’s in a name? Adding method to the madness
productmarketing
PRO
24
4.1k
The Impact of AI in SEO - AI Overviews June 2024 Edition
aleyda
5
1.1k
Information Architects: The Missing Link in Design Systems
soysaucechin
0
960
Everyday Curiosity
cassininazir
0
230
JAMstack: Web Apps at Ludicrous Speed - All Things Open 2022
reverentgeek
1
460
Responsive Adventures: Dirty Tricks From The Dark Corners of Front-End
smashingmag
254
22k
What does AI have to do with Human Rights?
axbom
PRO
1
2.2k
Raft: Consensus for Rubyists
vanstee
141
7.5k
Put a Button on it: Removing Barriers to Going Fast.
kastner
60
4.3k
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