SlideShare a Scribd company logo
<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

More Related Content

What's hot

C++ L01-Variables
C++ L01-VariablesC++ L01-Variables
C++ L01-Variables
Mohammad Shaker
 
C++ L05-Functions
C++ L05-FunctionsC++ L05-Functions
C++ L05-Functions
Mohammad Shaker
 
Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015
Iran Entrepreneurship Association
 
c programming
c programmingc programming
c programming
Arun Umrao
 
Hello Swift 3/5 - Function
Hello Swift 3/5 - FunctionHello Swift 3/5 - Function
Hello Swift 3/5 - Function
Cody Yun
 
C++ L09-Classes Part2
C++ L09-Classes Part2C++ L09-Classes Part2
C++ L09-Classes Part2
Mohammad Shaker
 
Free Monads Getting Started
Free Monads Getting StartedFree Monads Getting Started
Free Monads Getting Started
Kent Ohashi
 
はじめてのGroovy
はじめてのGroovyはじめてのGroovy
はじめてのGroovy
Tsuyoshi Yamamoto
 
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
The Software House
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
Giordano Scalzo
 
MP in Clojure
MP in ClojureMP in Clojure
MP in Clojure
Kent Ohashi
 
Lexical environment in ecma 262 5
Lexical environment in ecma 262 5Lexical environment in ecma 262 5
Lexical environment in ecma 262 5
Kim Hunmin
 
C++ L11-Polymorphism
C++ L11-PolymorphismC++ L11-Polymorphism
C++ L11-Polymorphism
Mohammad Shaker
 
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
The Software House
 
Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015
Lin Yo-An
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. Streams
DEVTYPE
 
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. Объекты, классы и пакеты в Java
DEVTYPE
 
C++ L06-Pointers
C++ L06-PointersC++ L06-Pointers
C++ L06-Pointers
Mohammad Shaker
 
C++ L07-Struct
C++ L07-StructC++ L07-Struct
C++ L07-Struct
Mohammad Shaker
 

What's hot (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
 

Similar to Generics and Inference

Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my day
Tor Ivry
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
진성 오
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
André Faria Gomes
 
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
Romain 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 3
Kirill Rozov
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
Paulo Morgado
 
Kotlin
KotlinKotlin
Scala 2 + 2 > 4
Scala 2 + 2 > 4Scala 2 + 2 > 4
Scala 2 + 2 > 4
Emil Vladev
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
Christian Baranowski
 
Scala on Your Phone
Scala on Your PhoneScala on Your Phone
Scala on Your Phone
Michael Galpin
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Dmitry Sheiko
 
20191116 custom operators in swift
20191116 custom operators in swift20191116 custom operators in swift
20191116 custom operators in swift
Chiwon Song
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry 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# 7
Paulo Morgado
 
Monads in Swift
Monads in SwiftMonads in Swift
Monads in Swift
Vincent Pradeilles
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
Arturo Herrero
 

Similar to Generics and 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
 

Recently uploaded

Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
The Third Creative Media
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
Tier1 app
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
Marcin Chrost
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
rodomar2
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
gapen1
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
Bert Jan Schrijver
 
The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
Yara Milbes
 
UI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design SystemUI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design System
Peter Muessig
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
Peter Muessig
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
kalichargn70th171
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
dakas1
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid
 
Quarter 3 SLRP grade 9.. gshajsbhhaheabh
Quarter 3 SLRP grade 9.. gshajsbhhaheabhQuarter 3 SLRP grade 9.. gshajsbhhaheabh
Quarter 3 SLRP grade 9.. gshajsbhhaheabh
aisafed42
 
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
kgyxske
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
Hornet Dynamics
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
Green Software Development
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
Sven Peters
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
kalichargn70th171
 

Recently uploaded (20)

Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
 
The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
 
UI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design SystemUI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design System
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
 
Quarter 3 SLRP grade 9.. gshajsbhhaheabh
Quarter 3 SLRP grade 9.. gshajsbhhaheabhQuarter 3 SLRP grade 9.. gshajsbhhaheabh
Quarter 3 SLRP grade 9.. gshajsbhhaheabh
 
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
 

Generics and 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>