SlideShare uma empresa Scribd logo
1 de 34
Baixar para ler offline
<Generics:
Inference>
<Generics: Inference>
→ Rich Fox @RGfox
→ I work at Propeller
→ I am a contributer to
Generics and the Art of Inferences
→ What are generics
→ What is inference
→ Goal of Talk
Ex 1. Casting Number Types
protocol NumberConvertible {
init(_ value: Int)
init(_ value: Float)
init(_ value: Double)
}
extension Double: NumberConvertible {}
extension Float: NumberConvertible {}
extension Int: NumberConvertible {}
Int,Float,Double: NumberConvertible
extension NumberConvertible {
func convert<T: NumberConvertible>() -> T {
switch self {
case let x as Float:
return T(x)
case let x as Int:
return T(x)
case let x as Double:
return T(x)
default:
fatalError("NumberConvertible convert failed!")
}
}
}
Cast by Inference!
let number = 5.5
let a: Float = number.convert()
let b: Int = number.convert()
let c: Double = number.convert()
let aa = number.convert() + Float(2)
let bb = number.convert() + Int(2)
let cc = number.convert() + Double(2)
Ex 2. Encoding/Decoding Structs
(Map and Inferences)
protocol Serializable {
init(construct: [String: Any])
func destruct() -> [String: Any]
}
extension Optional {
func unbox<T>() -> T? {
return self as? T
}
func unboxArray<T>() -> [T] {
return unbox() ?? []
}
}
struct SortItem {
let name: String
let subSorts: [SortItem]
}
extension SortItem: Serializable {
func destruct() -> [String: Any] {
var construct = [String: Any]()
construct["name"] = name
construct["subSorts"] = subSorts.map { $0.destruct() }
return construct
}
init(construct: [String: Any]) {
name = construct["name"].unbox() ?? ""
let sorts = construct["subSorts"]
.unboxArray()
!.map(SortItem.init)
}
}
struct SortItem {
let name: String
let subSorts: [SortItem]
}
extension SortItem: Serializable {
func destruct() -> [String: Any] {
var construct = [String: Any]()
construct["name"] = name
construct["subSorts"] = subSorts.map { $0.destruct() }
return construct
}
init(construct: [String: Any]) {
name = construct["name"].unbox() ?? ""
let sorts = construct["subSorts"]
.unboxArray()
!.map(SortItem.init(construct:))
}
}
struct SortItem {
let name: String
let subSorts: [SortItem]
//Default Value = Incognito
init(subSorts: [SortItem] = [], name: String) {
self.subSorts = subSorts
self.name = name
}
}
extension SortItem: Serializable {
func destruct() -> [String: Any] {
var construct = [String: Any]()
construct["name"] = name
construct["subSorts"] = subSorts.map { $0.destruct() }
return construct
}
init(construct: [String: Any]) {
name = construct["name"].unbox() ?? ""
let sorts = construct["subSorts"]
.unboxArray()
!.map(SortItem.init)
}
}
struct SortItem {
let name: String
let subSorts: [SortItem]
//Default Value = Incognito
init(subSorts: [SortItem] = [], name: String) {
self.subSorts = subSorts
self.name = name
}
}
extension SortItem: Serializable {
func destruct() -> [String: Any] {
var construct = [String: Any]()
construct["name"] = name
construct["subSorts"] = subSorts.map { $0.destruct() }
return construct
}
init(construct: [String: Any]) {
name = construct["name"].unbox() ?? ""
let sorts = construct["subSorts"]
.unboxArray()
.map(SortItem.init)
subSorts = sorts
}
}
Return type of unboxArray() inferred
through .map!
let sorts = construct["subSorts"]
.unboxArray()
.map(SortItem.init(construct:))
Ex 3: Promises/Networking
Result/Promise
→ Concise implementation
→ Result Enum
→ Promise Class w/AssociateType
enum Result<T> {
case error(BasicError),
some(T)
private func fire(target: Promise<T>) {
switch self {
case .error(let err):
target.failedAction?(err)
case .some(let val):
target.completeAction?(val)
}
}
}
final class Promise<T> {
private var completeAction: (T -> Void)?
private var failedAction: (BasicError -> Void)?
func complete(action: T! -> Void) -> Promise<T> {
completeAction = action
return self
}
func failure(action: BasicError -> Void) -> Promise<T> {
failedAction = action
return self
}
var trigger: Result<T>? {
didSet { trigger?.fire(self) }
}
}
Closure keeps Promise alive - waiting for trigger
Usage Example:
(Networking + Generics * Inference)
Promise on the Network:
func getUser(url: String) -> Promise<User> {
}
Promise on the Network:
func getUser(url: String) -> Promise<User> {
let promise = Promise<User>()
return promise
}
Promise on the Network:
func getUser(url: String) -> Promise<User> {
let promise = Promise<User>()
//Async call keeping reference to ˆpromiseˆ
makeGetRequest(url) { response in
}
return promise
}
Promise on the Network:
func getUser(url: String) -> Promise<User> {
let promise = Promise<User>()
//Async call keeping reference to ˆpromiseˆ
makeGetRequest(url) { response in
guard let json = response else {
Promise.trigger = Result.error(.unknown)
return
}
}
return promise
}
Promise on the Network:
func getUser(url: String) -> Promise<User> {
let promise = Promise<User>()
//Async call keeping reference to ˆpromiseˆ
makeGetRequest(url) { response in
guard let json = response else {
Promise.trigger = Result.error(.unknown)
return
}
if let user = try? User(object: json) {
Promise.trigger = Result.some(user)
}
}
return promise
}
Promise on the Network:
func getUser(url: String) -> Promise<User> {
let promise = Promise<User>()
//Async call keeping reference to ˆpromiseˆ
makeGetRequest(url) { response in
guard let json = response else {
Promise.trigger = Result.error(.unknown)
return
}
if let user = try? User(object: json) {
Promise.trigger = Result.some(user)
} else {
let error = BasicError(object: json)
Promise.trigger = Result.error(error)
}
}
return promise
}
More Generics and Inferred Promises
func getEncodableType<T: JSONDecodable>(url: String) -> Promise<T> {
let promise = Promise<T>()
//Async call keeping reference to ˆpromiseˆ
makeGetRequest(url) { response in
guard let json = response else {
Promise.trigger = Result.error(.unknown)
return
}
if let result = try? T(object: json) {
Promise.trigger = Result.some(result)
} else {
let error = BasicError(object: json)
Promise.trigger = Result.error(error)
}
}
return promise
}
More Generics and Inferred Promises
func getEncodableType<T: JSONDecodable>(url: String) -> Promise<T> {
let promise = Promise<T>() //Generic instead of User
//Async call keeping reference to ˆpromiseˆ
makeGetRequest(url) { response in
guard let json = response else {
Promise.trigger = Result.error(.unknown)
return
}
if let result = try? T(object: json) { //JSONDecodable init
Promise.trigger = Result.some(result)
} else {
let error = BasicError(object: json)
Promise.trigger = Result.error(error)
}
}
return promise
}
var user:User?
var guest:Guest?
func fetchPeople() {
let printError: BasicError -> Void =
{"error: ($0.message)"}
NetworkService.getEncodableType("/url/User")
.complete { user = $0 }
.failure(printError)
NetworkService.getEncodableType("/url/Guest")
.complete { guest = $0 }
.failure(printError)
}
Promise<T> inferred by complete:(T)->Void
NetworkService.getEncodableType("/url/User")
.complete { user = $0 }
New in Swift 3 Generics
Generic typealias
typealias StringDictionary<T> = Dictionary<String, T>
typealias BackwardTriple<T1,T2,T3> = (T3, T2, T1)
Limited: Generic closure Crashes Playground
typealias StringDictionaryValue<T> = (Dictionary<String, T>) -> T?
let testValue: StringDictionaryValue = { return $0["test"] }
New in Swift 3 Generics
Generic typealias
typealias StringDictionary<T> = Dictionary<String, T>
typealias BackwardTriple<T1,T2,T3> = (T3, T2, T1)
Function Works as Expected
typealias StringDictionary<T> = (Dictionary<String, T>)
func valueForKey<T>(dict:StringDictionary<T>, key: String) -> T? {
return dict[key]
}
Inference Concluded
1. Return Type Context
func convert<T: NumberConvertible>() -> T
2. Though map Function
.unboxArray()
.map(SortItem.init(construct:))
3. Through associatedtype Context
func complete(action: T! -> Void) ->
Promise<T>
Thank You
Forward Swift
@RGfox

Mais conteúdo relacionado

Mais procurados

Hello Swift 3/5 - Function
Hello Swift 3/5 - FunctionHello Swift 3/5 - Function
Hello Swift 3/5 - FunctionCody Yun
 
Free Monads Getting Started
Free Monads Getting StartedFree Monads Getting Started
Free Monads Getting StartedKent Ohashi
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoThe Software House
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to SwiftGiordano Scalzo
 
Lexical environment in ecma 262 5
Lexical environment in ecma 262 5Lexical environment in ecma 262 5
Lexical environment in ecma 262 5Kim Hunmin
 
Let the type system be your friend
Let the type system be your friendLet the type system be your friend
Let the type system be your friendThe Software House
 
Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015Lin Yo-An
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. StreamsDEVTYPE
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...ssuserd6b1fd
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в JavaDEVTYPE
 

Mais procurados (20)

C++ L01-Variables
C++ L01-VariablesC++ L01-Variables
C++ L01-Variables
 
C++ L05-Functions
C++ L05-FunctionsC++ L05-Functions
C++ L05-Functions
 
Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015
 
c programming
c programmingc programming
c programming
 
Hello Swift 3/5 - Function
Hello Swift 3/5 - FunctionHello Swift 3/5 - Function
Hello Swift 3/5 - Function
 
C++ L09-Classes Part2
C++ L09-Classes Part2C++ L09-Classes Part2
C++ L09-Classes Part2
 
Free Monads Getting Started
Free Monads Getting StartedFree Monads Getting Started
Free Monads Getting Started
 
はじめてのGroovy
はじめてのGroovyはじめてのGroovy
はじめてのGroovy
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duo
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
 
MP in Clojure
MP in ClojureMP in Clojure
MP in Clojure
 
Lexical environment in ecma 262 5
Lexical environment in ecma 262 5Lexical environment in ecma 262 5
Lexical environment in ecma 262 5
 
C++ L11-Polymorphism
C++ L11-PolymorphismC++ L11-Polymorphism
C++ L11-Polymorphism
 
Let the type system be your friend
Let the type system be your friendLet the type system be your friend
Let the type system be your friend
 
Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. Streams
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java
 
C++ L06-Pointers
C++ L06-PointersC++ L06-Pointers
C++ L06-Pointers
 
C++ L07-Struct
C++ L07-StructC++ L07-Struct
C++ L07-Struct
 

Semelhante a GENERICS INFERENCE

Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my dayTor Ivry
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기진성 오
 
Un dsl pour ma base de données
Un dsl pour ma base de donnéesUn dsl pour ma base de données
Un dsl pour ma base de donnéesRomain Lecomte
 
Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kirill Rozov
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
20191116 custom operators in swift
20191116 custom operators in swift20191116 custom operators in swift
20191116 custom operators in swiftChiwon Song
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Paulo Morgado
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with GroovyArturo Herrero
 

Semelhante a GENERICS INFERENCE (20)

Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my day
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
Un dsl pour ma base de données
Un dsl pour ma base de donnéesUn dsl pour ma base de données
Un dsl pour ma base de données
 
Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
 
Kotlin
KotlinKotlin
Kotlin
 
Scala 2 + 2 > 4
Scala 2 + 2 > 4Scala 2 + 2 > 4
Scala 2 + 2 > 4
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
Scala on Your Phone
Scala on Your PhoneScala on Your Phone
Scala on Your Phone
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
20191116 custom operators in swift
20191116 custom operators in swift20191116 custom operators in swift
20191116 custom operators in swift
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7
 
Monads in Swift
Monads in SwiftMonads in Swift
Monads in Swift
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 

Último

SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 

Último (20)

SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Odoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting ServiceOdoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting Service
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 

GENERICS INFERENCE

  • 2. <Generics: Inference> → Rich Fox @RGfox → I work at Propeller → I am a contributer to
  • 3. Generics and the Art of Inferences → What are generics → What is inference → Goal of Talk
  • 4. Ex 1. Casting Number Types
  • 5. protocol NumberConvertible { init(_ value: Int) init(_ value: Float) init(_ value: Double) } extension Double: NumberConvertible {} extension Float: NumberConvertible {} extension Int: NumberConvertible {} Int,Float,Double: NumberConvertible
  • 6. extension NumberConvertible { func convert<T: NumberConvertible>() -> T { switch self { case let x as Float: return T(x) case let x as Int: return T(x) case let x as Double: return T(x) default: fatalError("NumberConvertible convert failed!") } } }
  • 7. Cast by Inference! let number = 5.5 let a: Float = number.convert() let b: Int = number.convert() let c: Double = number.convert() let aa = number.convert() + Float(2) let bb = number.convert() + Int(2) let cc = number.convert() + Double(2)
  • 8. Ex 2. Encoding/Decoding Structs (Map and Inferences)
  • 9. protocol Serializable { init(construct: [String: Any]) func destruct() -> [String: Any] } extension Optional { func unbox<T>() -> T? { return self as? T } func unboxArray<T>() -> [T] { return unbox() ?? [] } }
  • 10. struct SortItem { let name: String let subSorts: [SortItem] } extension SortItem: Serializable { func destruct() -> [String: Any] { var construct = [String: Any]() construct["name"] = name construct["subSorts"] = subSorts.map { $0.destruct() } return construct } init(construct: [String: Any]) { name = construct["name"].unbox() ?? "" let sorts = construct["subSorts"] .unboxArray() !.map(SortItem.init) } }
  • 11. struct SortItem { let name: String let subSorts: [SortItem] } extension SortItem: Serializable { func destruct() -> [String: Any] { var construct = [String: Any]() construct["name"] = name construct["subSorts"] = subSorts.map { $0.destruct() } return construct } init(construct: [String: Any]) { name = construct["name"].unbox() ?? "" let sorts = construct["subSorts"] .unboxArray() !.map(SortItem.init(construct:)) } }
  • 12. struct SortItem { let name: String let subSorts: [SortItem] //Default Value = Incognito init(subSorts: [SortItem] = [], name: String) { self.subSorts = subSorts self.name = name } } extension SortItem: Serializable { func destruct() -> [String: Any] { var construct = [String: Any]() construct["name"] = name construct["subSorts"] = subSorts.map { $0.destruct() } return construct } init(construct: [String: Any]) { name = construct["name"].unbox() ?? "" let sorts = construct["subSorts"] .unboxArray() !.map(SortItem.init) } }
  • 13. struct SortItem { let name: String let subSorts: [SortItem] //Default Value = Incognito init(subSorts: [SortItem] = [], name: String) { self.subSorts = subSorts self.name = name } } extension SortItem: Serializable { func destruct() -> [String: Any] { var construct = [String: Any]() construct["name"] = name construct["subSorts"] = subSorts.map { $0.destruct() } return construct } init(construct: [String: Any]) { name = construct["name"].unbox() ?? "" let sorts = construct["subSorts"] .unboxArray() .map(SortItem.init) subSorts = sorts } }
  • 14. Return type of unboxArray() inferred through .map! let sorts = construct["subSorts"] .unboxArray() .map(SortItem.init(construct:))
  • 16. Result/Promise → Concise implementation → Result Enum → Promise Class w/AssociateType
  • 17. enum Result<T> { case error(BasicError), some(T) private func fire(target: Promise<T>) { switch self { case .error(let err): target.failedAction?(err) case .some(let val): target.completeAction?(val) } } }
  • 18. final class Promise<T> { private var completeAction: (T -> Void)? private var failedAction: (BasicError -> Void)? func complete(action: T! -> Void) -> Promise<T> { completeAction = action return self } func failure(action: BasicError -> Void) -> Promise<T> { failedAction = action return self } var trigger: Result<T>? { didSet { trigger?.fire(self) } } } Closure keeps Promise alive - waiting for trigger
  • 19. Usage Example: (Networking + Generics * Inference)
  • 20. Promise on the Network: func getUser(url: String) -> Promise<User> { }
  • 21. Promise on the Network: func getUser(url: String) -> Promise<User> { let promise = Promise<User>() return promise }
  • 22. Promise on the Network: func getUser(url: String) -> Promise<User> { let promise = Promise<User>() //Async call keeping reference to ˆpromiseˆ makeGetRequest(url) { response in } return promise }
  • 23. Promise on the Network: func getUser(url: String) -> Promise<User> { let promise = Promise<User>() //Async call keeping reference to ˆpromiseˆ makeGetRequest(url) { response in guard let json = response else { Promise.trigger = Result.error(.unknown) return } } return promise }
  • 24. Promise on the Network: func getUser(url: String) -> Promise<User> { let promise = Promise<User>() //Async call keeping reference to ˆpromiseˆ makeGetRequest(url) { response in guard let json = response else { Promise.trigger = Result.error(.unknown) return } if let user = try? User(object: json) { Promise.trigger = Result.some(user) } } return promise }
  • 25. Promise on the Network: func getUser(url: String) -> Promise<User> { let promise = Promise<User>() //Async call keeping reference to ˆpromiseˆ makeGetRequest(url) { response in guard let json = response else { Promise.trigger = Result.error(.unknown) return } if let user = try? User(object: json) { Promise.trigger = Result.some(user) } else { let error = BasicError(object: json) Promise.trigger = Result.error(error) } } return promise }
  • 26. More Generics and Inferred Promises func getEncodableType<T: JSONDecodable>(url: String) -> Promise<T> { let promise = Promise<T>() //Async call keeping reference to ˆpromiseˆ makeGetRequest(url) { response in guard let json = response else { Promise.trigger = Result.error(.unknown) return } if let result = try? T(object: json) { Promise.trigger = Result.some(result) } else { let error = BasicError(object: json) Promise.trigger = Result.error(error) } } return promise }
  • 27. More Generics and Inferred Promises func getEncodableType<T: JSONDecodable>(url: String) -> Promise<T> { let promise = Promise<T>() //Generic instead of User //Async call keeping reference to ˆpromiseˆ makeGetRequest(url) { response in guard let json = response else { Promise.trigger = Result.error(.unknown) return } if let result = try? T(object: json) { //JSONDecodable init Promise.trigger = Result.some(result) } else { let error = BasicError(object: json) Promise.trigger = Result.error(error) } } return promise }
  • 28. var user:User? var guest:Guest? func fetchPeople() { let printError: BasicError -> Void = {"error: ($0.message)"} NetworkService.getEncodableType("/url/User") .complete { user = $0 } .failure(printError) NetworkService.getEncodableType("/url/Guest") .complete { guest = $0 } .failure(printError) }
  • 29. Promise<T> inferred by complete:(T)->Void NetworkService.getEncodableType("/url/User") .complete { user = $0 }
  • 30. New in Swift 3 Generics Generic typealias typealias StringDictionary<T> = Dictionary<String, T> typealias BackwardTriple<T1,T2,T3> = (T3, T2, T1) Limited: Generic closure Crashes Playground typealias StringDictionaryValue<T> = (Dictionary<String, T>) -> T? let testValue: StringDictionaryValue = { return $0["test"] }
  • 31. New in Swift 3 Generics Generic typealias typealias StringDictionary<T> = Dictionary<String, T> typealias BackwardTriple<T1,T2,T3> = (T3, T2, T1) Function Works as Expected typealias StringDictionary<T> = (Dictionary<String, T>) func valueForKey<T>(dict:StringDictionary<T>, key: String) -> T? { return dict[key] }
  • 33. 1. Return Type Context func convert<T: NumberConvertible>() -> T 2. Though map Function .unboxArray() .map(SortItem.init(construct:)) 3. Through associatedtype Context func complete(action: T! -> Void) -> Promise<T>