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
Ad

More Related Content

What's hot (20)

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
 
Hello Swift 3/5 - Function
Hello Swift 3/5 - FunctionHello Swift 3/5 - Function
Hello Swift 3/5 - Function
Cody Yun
 
Free Monads Getting Started
Free Monads Getting StartedFree Monads Getting Started
Free Monads Getting Started
Kent 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 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
 
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
 
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
 

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
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
Kotlin
Jemo Mgebrishvili
 
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
 
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 함수 커링 사용하기
진성 오
 
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
 
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
 
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
 
Ad

Recently uploaded (20)

Programs as Values - Write code and don't get lost
Programs as Values - Write code and don't get lostPrograms as Values - Write code and don't get lost
Programs as Values - Write code and don't get lost
Pierangelo Cecchetto
 
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World ExamplesMastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
jamescantor38
 
Gojek Clone App for Multi-Service Business
Gojek Clone App for Multi-Service BusinessGojek Clone App for Multi-Service Business
Gojek Clone App for Multi-Service Business
XongoLab Technologies LLP
 
AEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural MeetingAEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural Meeting
jennaf3
 
Solar-wind hybrid engery a system sustainable power
Solar-wind  hybrid engery a system sustainable powerSolar-wind  hybrid engery a system sustainable power
Solar-wind hybrid engery a system sustainable power
bhoomigowda12345
 
Wilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For WindowsWilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For Windows
Google
 
Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025
GrapesTech Solutions
 
Digital Twins Software Service in Belfast
Digital Twins Software Service in BelfastDigital Twins Software Service in Belfast
Digital Twins Software Service in Belfast
julia smits
 
What Do Candidates Really Think About AI-Powered Recruitment Tools?
What Do Candidates Really Think About AI-Powered Recruitment Tools?What Do Candidates Really Think About AI-Powered Recruitment Tools?
What Do Candidates Really Think About AI-Powered Recruitment Tools?
HireME
 
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business StageA Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
SynapseIndia
 
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdfTop Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
evrigsolution
 
How to avoid IT Asset Management mistakes during implementation_PDF.pdf
How to avoid IT Asset Management mistakes during implementation_PDF.pdfHow to avoid IT Asset Management mistakes during implementation_PDF.pdf
How to avoid IT Asset Management mistakes during implementation_PDF.pdf
victordsane
 
Meet the New Kid in the Sandbox - Integrating Visualization with Prometheus
Meet the New Kid in the Sandbox - Integrating Visualization with PrometheusMeet the New Kid in the Sandbox - Integrating Visualization with Prometheus
Meet the New Kid in the Sandbox - Integrating Visualization with Prometheus
Eric D. Schabell
 
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
OnePlan Solutions
 
Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025
Phil Eaton
 
How I solved production issues with OpenTelemetry
How I solved production issues with OpenTelemetryHow I solved production issues with OpenTelemetry
How I solved production issues with OpenTelemetry
Cees Bos
 
Sequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptxSequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptx
aashrithakondapalli8
 
Buy vs. Build: Unlocking the right path for your training tech
Buy vs. Build: Unlocking the right path for your training techBuy vs. Build: Unlocking the right path for your training tech
Buy vs. Build: Unlocking the right path for your training tech
Rustici Software
 
Wilcom Embroidery Studio Crack Free Latest 2025
Wilcom Embroidery Studio Crack Free Latest 2025Wilcom Embroidery Studio Crack Free Latest 2025
Wilcom Embroidery Studio Crack Free Latest 2025
Web Designer
 
Beyond the code. Complexity - 2025.05 - SwiftCraft
Beyond the code. Complexity - 2025.05 - SwiftCraftBeyond the code. Complexity - 2025.05 - SwiftCraft
Beyond the code. Complexity - 2025.05 - SwiftCraft
Dmitrii Ivanov
 
Programs as Values - Write code and don't get lost
Programs as Values - Write code and don't get lostPrograms as Values - Write code and don't get lost
Programs as Values - Write code and don't get lost
Pierangelo Cecchetto
 
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World ExamplesMastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
jamescantor38
 
AEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural MeetingAEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural Meeting
jennaf3
 
Solar-wind hybrid engery a system sustainable power
Solar-wind  hybrid engery a system sustainable powerSolar-wind  hybrid engery a system sustainable power
Solar-wind hybrid engery a system sustainable power
bhoomigowda12345
 
Wilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For WindowsWilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For Windows
Google
 
Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025
GrapesTech Solutions
 
Digital Twins Software Service in Belfast
Digital Twins Software Service in BelfastDigital Twins Software Service in Belfast
Digital Twins Software Service in Belfast
julia smits
 
What Do Candidates Really Think About AI-Powered Recruitment Tools?
What Do Candidates Really Think About AI-Powered Recruitment Tools?What Do Candidates Really Think About AI-Powered Recruitment Tools?
What Do Candidates Really Think About AI-Powered Recruitment Tools?
HireME
 
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business StageA Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
SynapseIndia
 
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdfTop Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
evrigsolution
 
How to avoid IT Asset Management mistakes during implementation_PDF.pdf
How to avoid IT Asset Management mistakes during implementation_PDF.pdfHow to avoid IT Asset Management mistakes during implementation_PDF.pdf
How to avoid IT Asset Management mistakes during implementation_PDF.pdf
victordsane
 
Meet the New Kid in the Sandbox - Integrating Visualization with Prometheus
Meet the New Kid in the Sandbox - Integrating Visualization with PrometheusMeet the New Kid in the Sandbox - Integrating Visualization with Prometheus
Meet the New Kid in the Sandbox - Integrating Visualization with Prometheus
Eric D. Schabell
 
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
OnePlan Solutions
 
Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025
Phil Eaton
 
How I solved production issues with OpenTelemetry
How I solved production issues with OpenTelemetryHow I solved production issues with OpenTelemetry
How I solved production issues with OpenTelemetry
Cees Bos
 
Sequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptxSequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptx
aashrithakondapalli8
 
Buy vs. Build: Unlocking the right path for your training tech
Buy vs. Build: Unlocking the right path for your training techBuy vs. Build: Unlocking the right path for your training tech
Buy vs. Build: Unlocking the right path for your training tech
Rustici Software
 
Wilcom Embroidery Studio Crack Free Latest 2025
Wilcom Embroidery Studio Crack Free Latest 2025Wilcom Embroidery Studio Crack Free Latest 2025
Wilcom Embroidery Studio Crack Free Latest 2025
Web Designer
 
Beyond the code. Complexity - 2025.05 - SwiftCraft
Beyond the code. Complexity - 2025.05 - SwiftCraftBeyond the code. Complexity - 2025.05 - SwiftCraft
Beyond the code. Complexity - 2025.05 - SwiftCraft
Dmitrii Ivanov
 
Ad

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>
  翻译: