SlideShare ist ein Scribd-Unternehmen logo
1 von 28
Values, Protocols and Codables
Florent Vilmart
•
•
•
•
What we’ll cover
Disclaimer
I have no idea what I’m doin’
•
•
•
•
•
Parse SDK
not your average SDK
An API, to build API’s
Parse SDK iOS/OSX Parse Swift
Runtime Dynamism Compile-time Dynamism
Object Oriented PoP
NSObject struct
async (Bolts) sync
iOS/macOS/tvOS/watchOS Just Swift
Objective-C vs Swift
The past, the present…
o
An REST API is a contract
… but …
Object
Data
Data
Object
Serialize ⚠️💣
Send
Responds
💣 ⚠️ Deserialize
💥
💥
Any API Client…
Till today
T:
Encodable
Data
Data
U:
Decodable
JSONEncoder
Send
Responds
JSONDecoderFor Free!
For Free!
URLSession
REST with Swift 4
T: Encodable
URLSession
U: Decodable
Great spot to fake / mock your server!
Or datastore
Or anything really…
REST abstract
Encodable / Decodable
Strings, Numbers, enum, Arrays, Dictionaries (of Codables) …
Objects / Structs with only Codable’s
Custom *(through protocol conformance)
Implement CodingKeys for encoding subset
Composability
Codable’s
•
•
•
•
Encoders / Decoders
•
•
•
•
•
JSONEncoder / ParseEncoder
JSON and friends
Protocols
protocol Saving: Encodable {
associatedtype SavingType
func save(options: Options) throws -> SavingType
func save() throws -> SavingType
}
protocol Fetching: Decodable {
associatedtype FetchingType
func fetch(options: Options) throws -> FetchingType
func fetch() throws -> FetchingType
}
ObjectType Protocol
public protocol ObjectType: Fetching, Saving {
static var className: String { get }
var objectId: String? { get set }
var createdAt: Date? { get set }
var updatedAt: Date? { get set }
var ACL: ACL? { get set }
}
public extension ObjectType {
public func save(options: Options = []) throws -> Self {
return try Command<Self, SaveResponse>(method: .POST,
path: object.endpoint,
params: nil,
body: object)
.execute(options: options)
.map { $0.apply(self) }
}
}
Extensible
extension Saving {
typealias Callback = (Self.SavingType?, Error?) -> Void
func save(options: API.Options = [],
callback: @escaping Callback) {
runAsync(options: options,
function: self.save,
callback: callback)
}
}
runAsync
let queue = DispatchQueue(label: "org.parse-community.ParseSwift.async")
private func runAsync<T>(options: API.Options,
function: @escaping (API.Options) throws -> T?,
callback: @escaping (T?, Error?) -> Void) {
queue.async {
do {
callback(try function(options), nil)
} catch let e {
callback(nil, e)
}
}
}
As a SDK user
struct GameScore: ParseSwift.ObjectType {
//: Those are required for ObjectType
var objectId: String?
var createdAt: Date?
var updatedAt: Date?
var ACL: ACL?
//: Your own properties
var score: Int
//: a custom initializer
init(score: Int) {
self.score = score
}
}
let score = GameScore(score: 10)
guard let savedScore = try? score.save() else { fatalError() }
public struct Command<T, U>: Encodable where T: Encodable, U: Decodable {
let method: Method
let path: Endpoint
let params: [String: String?]?
let body: T?
public func data() throws -> Data? {
return try JSONEncoder().encode(body)
}
public func execute(options: Options) throws -> Response<U> {
return try options.executor.execute(command: self, options: options)
}
internal func decode(responseData: Data) throws -> Response<U> {
do {
return Response(object: try Decoder.json.decode(U.self, from: responseData))
} catch _ {
throw try Decoder.json.decode(ParseError.self, from: responseData)
}
}
}
Command
Commands
extension Command where T: ObjectType {
// MARK: custom encoding
func data() throws -> Data? {
return try API.Encoder.parse.encode(body)
}
}
struct Response<T> where T: Decodable {
let object: T
func map<U>(_ mapper: (T) throws -> U) rethrows -> U {
return try mapper(object)
}
}
Executor
extension API.Command {
internal func getURLRequest(options: API.Options) throws -> URLRequest {
/* build a URLRequest from the command */
}
}
extension URLSession: APIExecutor {
public func execute<T, U>(command: API.Command<T, U>,
options: API.Options) throws -> API.Response<U> {
let urlRequest = try command.getURLRequest(options: options)
let responseData = try self.syncDataTask(with: urlRequest)
return try command.decode(responseData: responseData)
}
}
•
•
•
•
•
About Async
A Quick Word on sync code
no async is the best async
extension URLSession {
internal func syncDataTask(with request: URLRequest) throws -> Data {
let semaphore = DispatchSemaphore(value: 0)
var data: Data?
var error: Error?
var response: URLResponse?
dataTask(with: request) { (responseData, urlResponse, responseError) in
data = responseData; error = responseError; response = urlResponse;
semaphore.signal()
}.resume()
semaphore.wait()
guard let responseData = data else {
guard let error = error else { // no err no res?
throw NSError(domain: "unknown", code: -1, userInfo: ["response": response!])
}
throw error
}
return responseData
}
}
🤦♀️
•
•
•
•
•
What’s next
Because all is not green!
Values, Protocols and Codables
Florent Vilmart

Weitere ähnliche Inhalte

Was ist angesagt?

Unleash your inner console cowboy
Unleash your inner console cowboyUnleash your inner console cowboy
Unleash your inner console cowboyKenneth Geisshirt
 
Migrating to Puppet 4.0
Migrating to Puppet 4.0Migrating to Puppet 4.0
Migrating to Puppet 4.0Puppet
 
Vim Script Programming
Vim Script ProgrammingVim Script Programming
Vim Script ProgrammingLin Yo-An
 
Ansible, Simplicity, and the Zen of Python
Ansible, Simplicity, and the Zen of PythonAnsible, Simplicity, and the Zen of Python
Ansible, Simplicity, and the Zen of Pythontoddmowen
 
(Practical) linux 104
(Practical) linux 104(Practical) linux 104
(Practical) linux 104Arie Bregman
 
BSDM with BASH: Command Interpolation
BSDM with BASH: Command InterpolationBSDM with BASH: Command Interpolation
BSDM with BASH: Command InterpolationWorkhorse Computing
 
BASH Variables Part 1: Basic Interpolation
BASH Variables Part 1: Basic InterpolationBASH Variables Part 1: Basic Interpolation
BASH Variables Part 1: Basic InterpolationWorkhorse Computing
 
Web Audio API + AngularJS
Web Audio API + AngularJSWeb Audio API + AngularJS
Web Audio API + AngularJSChris Bateman
 
Ansible for Beginners
Ansible for BeginnersAnsible for Beginners
Ansible for BeginnersArie Bregman
 
Keeping objects healthy with Object::Exercise.
Keeping objects healthy with Object::Exercise.Keeping objects healthy with Object::Exercise.
Keeping objects healthy with Object::Exercise.Workhorse Computing
 
Hypers and Gathers and Takes! Oh my!
Hypers and Gathers and Takes! Oh my!Hypers and Gathers and Takes! Oh my!
Hypers and Gathers and Takes! Oh my!Workhorse Computing
 
Ethiopian multiplication in Perl6
Ethiopian multiplication in Perl6Ethiopian multiplication in Perl6
Ethiopian multiplication in Perl6Workhorse Computing
 
Application Logging in the 21st century - 2014.key
Application Logging in the 21st century - 2014.keyApplication Logging in the 21st century - 2014.key
Application Logging in the 21st century - 2014.keyTim Bunce
 
JIP Pipeline System Introduction
JIP Pipeline System IntroductionJIP Pipeline System Introduction
JIP Pipeline System Introductionthasso23
 

Was ist angesagt? (20)

Unleash your inner console cowboy
Unleash your inner console cowboyUnleash your inner console cowboy
Unleash your inner console cowboy
 
Migrating to Puppet 4.0
Migrating to Puppet 4.0Migrating to Puppet 4.0
Migrating to Puppet 4.0
 
Vim Script Programming
Vim Script ProgrammingVim Script Programming
Vim Script Programming
 
Ansible, Simplicity, and the Zen of Python
Ansible, Simplicity, and the Zen of PythonAnsible, Simplicity, and the Zen of Python
Ansible, Simplicity, and the Zen of Python
 
(Practical) linux 104
(Practical) linux 104(Practical) linux 104
(Practical) linux 104
 
BSDM with BASH: Command Interpolation
BSDM with BASH: Command InterpolationBSDM with BASH: Command Interpolation
BSDM with BASH: Command Interpolation
 
BASH Variables Part 1: Basic Interpolation
BASH Variables Part 1: Basic InterpolationBASH Variables Part 1: Basic Interpolation
BASH Variables Part 1: Basic Interpolation
 
Nginx-lua
Nginx-luaNginx-lua
Nginx-lua
 
Web Audio API + AngularJS
Web Audio API + AngularJSWeb Audio API + AngularJS
Web Audio API + AngularJS
 
Ansible for Beginners
Ansible for BeginnersAnsible for Beginners
Ansible for Beginners
 
Keeping objects healthy with Object::Exercise.
Keeping objects healthy with Object::Exercise.Keeping objects healthy with Object::Exercise.
Keeping objects healthy with Object::Exercise.
 
Hypers and Gathers and Takes! Oh my!
Hypers and Gathers and Takes! Oh my!Hypers and Gathers and Takes! Oh my!
Hypers and Gathers and Takes! Oh my!
 
Ethiopian multiplication in Perl6
Ethiopian multiplication in Perl6Ethiopian multiplication in Perl6
Ethiopian multiplication in Perl6
 
Findbin libs
Findbin libsFindbin libs
Findbin libs
 
Metadata-driven Testing
Metadata-driven TestingMetadata-driven Testing
Metadata-driven Testing
 
Application Logging in the 21st century - 2014.key
Application Logging in the 21st century - 2014.keyApplication Logging in the 21st century - 2014.key
Application Logging in the 21st century - 2014.key
 
JIP Pipeline System Introduction
JIP Pipeline System IntroductionJIP Pipeline System Introduction
JIP Pipeline System Introduction
 
Linux networking
Linux networkingLinux networking
Linux networking
 
x86
x86x86
x86
 
DevOps with Fabric
DevOps with FabricDevOps with Fabric
DevOps with Fabric
 

Ähnlich wie Value protocols and codables

Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojureAbbas Raza
 
devLink - What's New in C# 4?
devLink - What's New in C# 4?devLink - What's New in C# 4?
devLink - What's New in C# 4?Kevin Pilch
 
"ClojureScript journey: from little script, to CLI program, to AWS Lambda fun...
"ClojureScript journey: from little script, to CLI program, to AWS Lambda fun..."ClojureScript journey: from little script, to CLI program, to AWS Lambda fun...
"ClojureScript journey: from little script, to CLI program, to AWS Lambda fun...Julia Cherniak
 
Clojure: Simple By Design
Clojure: Simple By DesignClojure: Simple By Design
Clojure: Simple By DesignAll Things Open
 
.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#Bertrand Le Roy
 
Building a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to SpaceBuilding a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to SpaceMaarten Balliauw
 
A Replay Approach to Software Validation
A Replay Approach to Software ValidationA Replay Approach to Software Validation
A Replay Approach to Software ValidationJames Pascoe
 
PDC Video on C# 4.0 Futures
PDC Video on C# 4.0 FuturesPDC Video on C# 4.0 Futures
PDC Video on C# 4.0 Futuresnithinmohantk
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAdam Getchell
 
Who killed object oriented design?
Who killed object oriented design?Who killed object oriented design?
Who killed object oriented design?Amir Barylko
 
Scalding big ADta
Scalding big ADtaScalding big ADta
Scalding big ADtab0ris_1
 
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017Codemotion
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Juan Pablo
 
Track c-High speed transaction-based hw-sw coverification -eve
Track c-High speed transaction-based hw-sw coverification -eveTrack c-High speed transaction-based hw-sw coverification -eve
Track c-High speed transaction-based hw-sw coverification -evechiportal
 
iPhone Development Intro
iPhone Development IntroiPhone Development Intro
iPhone Development IntroLuis Azevedo
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineRicardo Silva
 

Ähnlich wie Value protocols and codables (20)

Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
devLink - What's New in C# 4?
devLink - What's New in C# 4?devLink - What's New in C# 4?
devLink - What's New in C# 4?
 
"ClojureScript journey: from little script, to CLI program, to AWS Lambda fun...
"ClojureScript journey: from little script, to CLI program, to AWS Lambda fun..."ClojureScript journey: from little script, to CLI program, to AWS Lambda fun...
"ClojureScript journey: from little script, to CLI program, to AWS Lambda fun...
 
Clojure: Simple By Design
Clojure: Simple By DesignClojure: Simple By Design
Clojure: Simple By Design
 
.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#
 
Building a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to SpaceBuilding a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to Space
 
A Replay Approach to Software Validation
A Replay Approach to Software ValidationA Replay Approach to Software Validation
A Replay Approach to Software Validation
 
PDC Video on C# 4.0 Futures
PDC Video on C# 4.0 FuturesPDC Video on C# 4.0 Futures
PDC Video on C# 4.0 Futures
 
Codable routing
Codable routingCodable routing
Codable routing
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
 
Clean Code 2
Clean Code 2Clean Code 2
Clean Code 2
 
Who killed object oriented design?
Who killed object oriented design?Who killed object oriented design?
Who killed object oriented design?
 
Scalding big ADta
Scalding big ADtaScalding big ADta
Scalding big ADta
 
A Life of breakpoint
A Life of breakpointA Life of breakpoint
A Life of breakpoint
 
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
 
Track c-High speed transaction-based hw-sw coverification -eve
Track c-High speed transaction-based hw-sw coverification -eveTrack c-High speed transaction-based hw-sw coverification -eve
Track c-High speed transaction-based hw-sw coverification -eve
 
iPhone Development Intro
iPhone Development IntroiPhone Development Intro
iPhone Development Intro
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
 
C# Today and Tomorrow
C# Today and TomorrowC# Today and Tomorrow
C# Today and Tomorrow
 

Kürzlich hochgeladen

%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...masabamasaba
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benonimasabamasaba
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxAnnaArtyushina1
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyviewmasabamasaba
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in sowetomasabamasaba
 

Kürzlich hochgeladen (20)

%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 

Value protocols and codables

  • 1. Values, Protocols and Codables Florent Vilmart
  • 3. Disclaimer I have no idea what I’m doin’
  • 5. An API, to build API’s
  • 6. Parse SDK iOS/OSX Parse Swift Runtime Dynamism Compile-time Dynamism Object Oriented PoP NSObject struct async (Bolts) sync iOS/macOS/tvOS/watchOS Just Swift Objective-C vs Swift The past, the present…
  • 7. o
  • 8.
  • 9. An REST API is a contract … but …
  • 10. Object Data Data Object Serialize ⚠️💣 Send Responds 💣 ⚠️ Deserialize 💥 💥 Any API Client… Till today
  • 12. T: Encodable URLSession U: Decodable Great spot to fake / mock your server! Or datastore Or anything really… REST abstract
  • 13. Encodable / Decodable Strings, Numbers, enum, Arrays, Dictionaries (of Codables) … Objects / Structs with only Codable’s Custom *(through protocol conformance) Implement CodingKeys for encoding subset Composability Codable’s
  • 16.
  • 17. Protocols protocol Saving: Encodable { associatedtype SavingType func save(options: Options) throws -> SavingType func save() throws -> SavingType } protocol Fetching: Decodable { associatedtype FetchingType func fetch(options: Options) throws -> FetchingType func fetch() throws -> FetchingType }
  • 18. ObjectType Protocol public protocol ObjectType: Fetching, Saving { static var className: String { get } var objectId: String? { get set } var createdAt: Date? { get set } var updatedAt: Date? { get set } var ACL: ACL? { get set } } public extension ObjectType { public func save(options: Options = []) throws -> Self { return try Command<Self, SaveResponse>(method: .POST, path: object.endpoint, params: nil, body: object) .execute(options: options) .map { $0.apply(self) } } }
  • 19. Extensible extension Saving { typealias Callback = (Self.SavingType?, Error?) -> Void func save(options: API.Options = [], callback: @escaping Callback) { runAsync(options: options, function: self.save, callback: callback) } }
  • 20. runAsync let queue = DispatchQueue(label: "org.parse-community.ParseSwift.async") private func runAsync<T>(options: API.Options, function: @escaping (API.Options) throws -> T?, callback: @escaping (T?, Error?) -> Void) { queue.async { do { callback(try function(options), nil) } catch let e { callback(nil, e) } } }
  • 21. As a SDK user struct GameScore: ParseSwift.ObjectType { //: Those are required for ObjectType var objectId: String? var createdAt: Date? var updatedAt: Date? var ACL: ACL? //: Your own properties var score: Int //: a custom initializer init(score: Int) { self.score = score } } let score = GameScore(score: 10) guard let savedScore = try? score.save() else { fatalError() }
  • 22. public struct Command<T, U>: Encodable where T: Encodable, U: Decodable { let method: Method let path: Endpoint let params: [String: String?]? let body: T? public func data() throws -> Data? { return try JSONEncoder().encode(body) } public func execute(options: Options) throws -> Response<U> { return try options.executor.execute(command: self, options: options) } internal func decode(responseData: Data) throws -> Response<U> { do { return Response(object: try Decoder.json.decode(U.self, from: responseData)) } catch _ { throw try Decoder.json.decode(ParseError.self, from: responseData) } } } Command
  • 23. Commands extension Command where T: ObjectType { // MARK: custom encoding func data() throws -> Data? { return try API.Encoder.parse.encode(body) } } struct Response<T> where T: Decodable { let object: T func map<U>(_ mapper: (T) throws -> U) rethrows -> U { return try mapper(object) } }
  • 24. Executor extension API.Command { internal func getURLRequest(options: API.Options) throws -> URLRequest { /* build a URLRequest from the command */ } } extension URLSession: APIExecutor { public func execute<T, U>(command: API.Command<T, U>, options: API.Options) throws -> API.Response<U> { let urlRequest = try command.getURLRequest(options: options) let responseData = try self.syncDataTask(with: urlRequest) return try command.decode(responseData: responseData) } }
  • 26. A Quick Word on sync code no async is the best async extension URLSession { internal func syncDataTask(with request: URLRequest) throws -> Data { let semaphore = DispatchSemaphore(value: 0) var data: Data? var error: Error? var response: URLResponse? dataTask(with: request) { (responseData, urlResponse, responseError) in data = responseData; error = responseError; response = urlResponse; semaphore.signal() }.resume() semaphore.wait() guard let responseData = data else { guard let error = error else { // no err no res? throw NSError(domain: "unknown", code: -1, userInfo: ["response": response!]) } throw error } return responseData } } 🤦♀️
  • 28. Values, Protocols and Codables Florent Vilmart

Hinweis der Redaktion

  1. - Many of you may have already used, it - Schema less
  2. Unlike other SDK’s like FB/Github, schemas are not defined by us We provide the facility to create custom schemas Which makes the whole shebang quite more difficult. But, we know response types, error codes, bare minimal object (objectId, createdAt… , errors, responses)
  3. start with those 2 fundamental protocols Becaust that’s the base (for files and object and Pointers etc…) Provides the abstraction necessary. Could add Destroying but … Easily extensible
  4. - Encodable, because batch API 🤓 - params is [String: String?]? 😪 (QueryStringEncoder?) - tied to HTTP semantics 🤷🏻‍♀️ - executor in options func data() throws -> Data? Response (simple wrapper) I cannot subclass, butt……
  5. not a big fan of deps of deps of deps taking a side, is usually hindering adoption Who’S better? Rx, Reactive, Bolts, PromiseKit… Don’t care much