SlideShare une entreprise Scribd logo
1  sur  47
Télécharger pour lire hors ligne
Hidden Gems
in Swift
@akashivskyy
Agenda
‣ Literal Convertibles
‣ String Interpolation
‣ Pattern Matching
‣ Reflection
‣ Objective-C Bridging
Literal
Convertibles
Literal convertibles
struct RegularExpression {
let pattern: String
init(pattern: String)
}
let emailRegex = RegularExpression(
pattern: "^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}$"
)
// would be nice
let emailRegex = "^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}$"
1.0
String literal convertible
extension RegularExpression: StringLiteralConvertible {
typealias StringLiteralType = String
init(stringLiteral value: StringLiteralType) {
self.pattern = value
}
}
extension RegularExpression: ExtendedGraphemeClusterLiteralConvertible
extension RegularExpression: UnicodeScalarLiteralConvertible
1.0
All kinds of literals
‣ Array – Array, ArraySlice, Set
‣ Boolean – Bool, ObjCBool
‣ Dictionary – Dictionary, DictionaryLiteral
‣ Float – Float, Double
‣ Nil – Optional, Selector, Pointer
‣ Integer – Int, UInt, Float, Double
‣ String – String, Character, Selector
String
Interpolation
String interpolation
enum Byte: UInt8 {
case Zero = 0
case One = 1
}
let string = "(Byte.Zero)" // "Byte.Zero"
// would be nice
let string = "(Byte.Zero)" // "0"
1.0
Interpolation convertible
extension String /* : StringInterpolationConvertible */ {
init(stringInterpolationSegment byte: Byte) {
self = "(byte.rawValue)"
}
}
let string = "(Byte.Zero)" // "0"
1.0
Pattern

Matching
What are patterns?
‣ Enumeration cases
‣ Single equatable values
‣ Ranges and intervals
‣ Value bindings
‣ Type casts
‣ func ~= <T, U> (lhs: T, rhs: U) -> Bool
‣ Tuples of anything above
What are patterns?
‣ Enumeration cases
‣ Single equatable values
‣ Ranges and intervals
‣ Value bindings
‣ Type casts
‣ func ~= <T, U> (lhs: T, rhs: U) -> Bool
‣ Tuples of anything above
Where do we use them?
‣ Switch statements
‣ If-let bindings
‣ For-in loops
‣ Catch statements
case
let point = (1, 2)
switch point {
case (0, 0):
println("origin")
default:
println("arbitrary point")
}
1.0
case let where
let point = (3, 4)
switch point {
case let (x, y) where x == y:
println("point on x = y line")
default:
println("arbitrary point")
}
1.0
if let where
let point: (Int, Int)? = maybePoint()
if let (_, y) = point where y > 0 {
println("point above x axis")
}
1.2
for in where
let points = [
(1, 2),
(-3, 4),
(5, -6),
(-7, -8),
(9, 10)
]
for (x, y) in points where x > 0 && y > 0 {
println("point in 1st quadrant: ((x), (y))")
}
1.2
if case
let point = (5, 6)
let (width, height) = (
Int(UIScreen.mainScreen().bounds.width),
Int(UIScreen.mainScreen().bounds.height)
)
if case (0 ... width, 0 ... height) = point {
print("point on screen")
}
2.0
if case let where
let point = (7, 8)
if case let (x, 1 ..< Int.max) = point where x < 0 {
print("point in 2nd quadrant")
}
2.0
if case let where
switch subject {
case pattern where condition:
// becomes
if case pattern = subject where condition {
// multiple cases not yet supported
if case pattern1, pattern2 = subject { // compiler error
2.0
for case let in where
let points: [(Int, Int)?] = maybePoints()
for case .Some(let (x, y)) in points where x < 0 && y < 0 {
print("point in 3rd quadrant: ((x), (y))")
}
2.0
for case let in where
for element in subject {
if case pattern = element where condition {
// becomes
for case pattern in subject where condition {
// multiple cases not yet supported
for case pattern1, pattern2 in subject { // compiler error
2.0
Reflection
Default behavior
struct Vector {
typealias Point = (x: Double, y: Double)
let start: Point
let end: Point
var length: Double {
return sqrt(pow(end.x - start.x, 2) + pow(end.y - start.y, 2))
}
}
let unitVector = Vector(start: (0, 0), end: (1, 1))
2.0
Default behavior 2.0
(.0 0, .1 0)
(.0 1, .1 1)
Reflection methods
‣ Custom description
‣ Custom children tree
‣ Custom Quick Look preview
Custom description
extension Vector: CustomStringConvertible {
var description: String {
return "((start.x) × (start.y)) → ((end.x) × (end.y))"
}
}
2.0
Custom description 2.0
"(0.0 × 0.0) → (1.0 × 1.0)"
Custom mirror
extension Vector: CustomReflectable {
func customMirror() -> Mirror {
return Mirror(self, children: [
"start": "(start.x) × (start.y)",
"end": "(end.x) × (end.y)",
"length": length
])
}
}
2.0
Custom mirror 2.0
start "0.0 × 0.0"
end "1.0 × 1.0"
length 1.414213562373095
Custom preview
extension Vector: CustomPlaygroundQuickLookable {
func customPlaygroundQuickLook() -> PlaygroundQuickLook {
var bezierPath = UIBezierPath()
// draw the path
return .BezierPath(bezierPath)
}
}
2.0
Custom preview 2.0
Reflection principles
‣ Overrides default type descriptors
‣ Provides rich visualization
‣ Read-only
Objective-C
Bridging
Available bridging methods
‣ Inherit from Objective-C classes
‣ @objc attribute
‣ Bridging headers
‣ …and that’s basically it
Or is it?
@interface NSArray<Element> : NSObject // objective-c class
@end
struct Array<Element> { // generic swift struct
}
let swiftArray: [Int]
let objcArray = swiftArray as NSArray // no problem
2.0
Or is it?
@interface NSArray : NSObject
@end
struct Array<Element>: _ObjectiveCBridgeable {
}
let swiftArray: [Int]
let objcArray = swiftArray as NSArray
2.0
Bridgeable
protocol _ObjectiveCBridgeable {
typealias _ObjectiveCType
static func _isBridgedToObjectiveC() -> Bool
static func _getObjectiveCType() -> Any.Type
func _bridgeToObjectiveC() -> _ObjectiveCType
static func _forceBridgeFromObjectiveC(...)
static func _conditionallyBridgeFromObjectiveC(...)
}
2.0
Bridgeable
@interface XYZPoint : NSObject
- (instancetype)initWithX:(double)x y:(double)y;
@property double x;
@property double y;
@end
struct Point {
let x: Double
let y: Double
}
2.0
extension Point: _ObjectiveCBridgeable {
typealias _ObjectiveCType = XYZPoint
static func _isBridgedToObjectiveC() -> Bool {
return true
}
static func _getObjectiveCType() -> Any.Type {
return _ObjectiveCType.self
}
func _bridgeToObjectiveC() -> _ObjectiveCType {
return XYZPoint(x: x, y: y)
}
static func _forceBridgeFromObjectiveC(source: _ObjectiveCType, inout result: Point?) {
result = Point(x: source.x, y: source.y)
}
static func _conditionallyBridgeFromObjectiveC(source: _ObjectiveCType, inout result: Point?) -> Bool {
_forceBridgeFromObjectiveC(source, result: &result)
return true
}
}
2.0
Bridgeable
let objcPoint = XYZPoint(x: 1, y: 2)
if let swiftPoint = objcPoint as? Point {
// that's right
}
let objcPoint = XYZPoint(x: 3, y: 4)
let swiftPoint = objcPoint as Point // yeah
let swiftPoint = Point(x: 5, y: 6)
let objcPoint = swiftPoint as XYZPoint // hell yeah
let point: XYZPoint = Point(x: 7, y: 8) // mind: blown
2.0
Recap
‣ Literal Convertibles
‣ String Interpolation
‣ Pattern Matching
‣ Reflection
‣ Objective-C Bridging
How to learn the gems
‣ Carefully read Xcode release notes
‣ Follow right people on Twitter
‣ Study Swift module interface
‣ Use LLDB type lookup
‣ Experiment in playgrounds
Questions?
@akashivskyy
github.com/akashivskyy/talks
Thanks! 🍻
@akashivskyy
github.com/akashivskyy/talks

Contenu connexe

Tendances

Model-Driven Software Development - Static Analysis & Error Checking
Model-Driven Software Development - Static Analysis & Error CheckingModel-Driven Software Development - Static Analysis & Error Checking
Model-Driven Software Development - Static Analysis & Error Checking
Eelco Visser
 

Tendances (20)

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
 
Model-Driven Software Development - Static Analysis & Error Checking
Model-Driven Software Development - Static Analysis & Error CheckingModel-Driven Software Development - Static Analysis & Error Checking
Model-Driven Software Development - Static Analysis & Error Checking
 
C++ L11-Polymorphism
C++ L11-PolymorphismC++ L11-Polymorphism
C++ L11-Polymorphism
 
Variables, expressions, standard types
 Variables, expressions, standard types  Variables, expressions, standard types
Variables, expressions, standard types
 
RESTful API using scalaz (3)
RESTful API using scalaz (3)RESTful API using scalaz (3)
RESTful API using scalaz (3)
 
Oops lab manual2
Oops lab manual2Oops lab manual2
Oops lab manual2
 
Swift で JavaScript 始めませんか? #iOSDC
Swift で JavaScript 始めませんか? #iOSDCSwift で JavaScript 始めませんか? #iOSDC
Swift で JavaScript 始めませんか? #iOSDC
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL Databases
 
C++ L08-Classes Part1
C++ L08-Classes Part1C++ L08-Classes Part1
C++ L08-Classes Part1
 
Collection v3
Collection v3Collection v3
Collection v3
 
7 Habits For a More Functional Swift
7 Habits For a More Functional Swift7 Habits For a More Functional Swift
7 Habits For a More Functional Swift
 
Standford 2015 week9
Standford 2015 week9Standford 2015 week9
Standford 2015 week9
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
 
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
 
Bind me if you can
Bind me if you canBind me if you can
Bind me if you can
 
Standford 2015 week3: Objective-C Compatibility, Property List, Views
Standford 2015 week3: Objective-C Compatibility, Property List, ViewsStandford 2015 week3: Objective-C Compatibility, Property List, Views
Standford 2015 week3: Objective-C Compatibility, Property List, Views
 
Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013
 
Objective-Cひとめぐり
Objective-CひとめぐりObjective-Cひとめぐり
Objective-Cひとめぐり
 
Property-based testing
Property-based testingProperty-based testing
Property-based testing
 

En vedette

Strategia w Social Media w 6 krokach
Strategia w Social Media w 6 krokachStrategia w Social Media w 6 krokach
Strategia w Social Media w 6 krokach
Filip Cieslak
 
Blogi w firmie
Blogi w firmieBlogi w firmie
Blogi w firmie
Netguru
 
Rozwijanie firmy web developerskiej - Kuba Filipowski, Wiktor Schmidt, Netguru
Rozwijanie firmy web developerskiej - Kuba Filipowski, Wiktor Schmidt, NetguruRozwijanie firmy web developerskiej - Kuba Filipowski, Wiktor Schmidt, Netguru
Rozwijanie firmy web developerskiej - Kuba Filipowski, Wiktor Schmidt, Netguru
Biznes 2.0
 

En vedette (8)

Strategia w Social Media w 6 krokach
Strategia w Social Media w 6 krokachStrategia w Social Media w 6 krokach
Strategia w Social Media w 6 krokach
 
KISS Augmented Reality
KISS Augmented RealityKISS Augmented Reality
KISS Augmented Reality
 
Why Would A Programmer Fall In Love With SPA?
Why Would A Programmer Fall In Love With SPA?Why Would A Programmer Fall In Love With SPA?
Why Would A Programmer Fall In Love With SPA?
 
Payments integration: Stripe & Taxamo
Payments integration: Stripe & TaxamoPayments integration: Stripe & Taxamo
Payments integration: Stripe & Taxamo
 
Blogi w firmie
Blogi w firmieBlogi w firmie
Blogi w firmie
 
Czy Project Manger Musi Być Osobą Techniczną?
Czy Project Manger Musi Być Osobą Techniczną?Czy Project Manger Musi Być Osobą Techniczną?
Czy Project Manger Musi Być Osobą Techniczną?
 
301 Adam Zygadlewicz
301 Adam Zygadlewicz301 Adam Zygadlewicz
301 Adam Zygadlewicz
 
Rozwijanie firmy web developerskiej - Kuba Filipowski, Wiktor Schmidt, Netguru
Rozwijanie firmy web developerskiej - Kuba Filipowski, Wiktor Schmidt, NetguruRozwijanie firmy web developerskiej - Kuba Filipowski, Wiktor Schmidt, Netguru
Rozwijanie firmy web developerskiej - Kuba Filipowski, Wiktor Schmidt, Netguru
 

Similaire à Hidden Gems in Swift

The Art Of Readable Code
The Art Of Readable CodeThe Art Of Readable Code
The Art Of Readable Code
Baidu, Inc.
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
Tomasz Wrobel
 
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
 

Similaire à Hidden Gems in Swift (20)

Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
 
Idioms in swift 2016 05c
Idioms in swift 2016 05cIdioms in swift 2016 05c
Idioms in swift 2016 05c
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risks
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
The Art Of Readable Code
The Art Of Readable CodeThe Art Of Readable Code
The Art Of Readable Code
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
Cpp tutorial
Cpp tutorialCpp tutorial
Cpp tutorial
 
The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196
 
CppTutorial.ppt
CppTutorial.pptCppTutorial.ppt
CppTutorial.ppt
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
 
Getting started with ES6
Getting started with ES6Getting started with ES6
Getting started with ES6
 
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
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 

Plus de Netguru

Paradygmaty Programowania: Czy Istnieje Najlepszy?
Paradygmaty Programowania: Czy Istnieje Najlepszy?Paradygmaty Programowania: Czy Istnieje Najlepszy?
Paradygmaty Programowania: Czy Istnieje Najlepszy?
Netguru
 
Coffeescript presentation DublinJS
Coffeescript presentation DublinJSCoffeescript presentation DublinJS
Coffeescript presentation DublinJS
Netguru
 

Plus de Netguru (20)

Defining DSL (Domain Specific Language) using Ruby
Defining DSL (Domain Specific Language) using RubyDefining DSL (Domain Specific Language) using Ruby
Defining DSL (Domain Specific Language) using Ruby
 
How To Build Great Relationships With Your Clients
How To Build Great Relationships With Your ClientsHow To Build Great Relationships With Your Clients
How To Build Great Relationships With Your Clients
 
Agile Retrospectives
Agile RetrospectivesAgile Retrospectives
Agile Retrospectives
 
Ruby Rails Overview
Ruby Rails OverviewRuby Rails Overview
Ruby Rails Overview
 
From Birds To Bugs: Testowanie Z Pasją
From Birds To Bugs: Testowanie Z PasjąFrom Birds To Bugs: Testowanie Z Pasją
From Birds To Bugs: Testowanie Z Pasją
 
Communication With Clients Throughout The Project
Communication With Clients Throughout The ProjectCommunication With Clients Throughout The Project
Communication With Clients Throughout The Project
 
Everyday Rails
Everyday RailsEveryday Rails
Everyday Rails
 
Estimation myths debunked
Estimation myths debunkedEstimation myths debunked
Estimation myths debunked
 
Programming Paradigms Which One Is The Best?
Programming Paradigms Which One Is The Best?Programming Paradigms Which One Is The Best?
Programming Paradigms Which One Is The Best?
 
Z 50 do 100 w ciągu roku Jak rekrutować w IT?
Z 50 do 100 w ciągu roku Jak rekrutować w IT?Z 50 do 100 w ciągu roku Jak rekrutować w IT?
Z 50 do 100 w ciągu roku Jak rekrutować w IT?
 
Paradygmaty Programowania: Czy Istnieje Najlepszy?
Paradygmaty Programowania: Czy Istnieje Najlepszy?Paradygmaty Programowania: Czy Istnieje Najlepszy?
Paradygmaty Programowania: Czy Istnieje Najlepszy?
 
CSS architecture: How To Write Clean & Scalable Code
CSS architecture: How To Write Clean & Scalable CodeCSS architecture: How To Write Clean & Scalable Code
CSS architecture: How To Write Clean & Scalable Code
 
Ruby On Rails Intro
Ruby On Rails IntroRuby On Rails Intro
Ruby On Rails Intro
 
Perfect Project Read Me (in a few steps)
Perfect Project Read Me (in a few steps)Perfect Project Read Me (in a few steps)
Perfect Project Read Me (in a few steps)
 
The Git Basics
The Git BasicsThe Git Basics
The Git Basics
 
From nil to guru: intro to Ruby on Rails
From nil to guru: intro to Ruby on RailsFrom nil to guru: intro to Ruby on Rails
From nil to guru: intro to Ruby on Rails
 
Working With Teams Across The Borders
Working With Teams Across The BordersWorking With Teams Across The Borders
Working With Teams Across The Borders
 
Front-End Dev Tools
Front-End Dev ToolsFront-End Dev Tools
Front-End Dev Tools
 
OOScss Architecture For Rails Apps
OOScss Architecture For Rails AppsOOScss Architecture For Rails Apps
OOScss Architecture For Rails Apps
 
Coffeescript presentation DublinJS
Coffeescript presentation DublinJSCoffeescript presentation DublinJS
Coffeescript presentation DublinJS
 

Dernier

Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 

Dernier (20)

WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 

Hidden Gems in Swift

  • 3. Agenda ‣ Literal Convertibles ‣ String Interpolation ‣ Pattern Matching ‣ Reflection ‣ Objective-C Bridging
  • 5. Literal convertibles struct RegularExpression { let pattern: String init(pattern: String) } let emailRegex = RegularExpression( pattern: "^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}$" ) // would be nice let emailRegex = "^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}$" 1.0
  • 6. String literal convertible extension RegularExpression: StringLiteralConvertible { typealias StringLiteralType = String init(stringLiteral value: StringLiteralType) { self.pattern = value } } extension RegularExpression: ExtendedGraphemeClusterLiteralConvertible extension RegularExpression: UnicodeScalarLiteralConvertible 1.0
  • 7. All kinds of literals ‣ Array – Array, ArraySlice, Set ‣ Boolean – Bool, ObjCBool ‣ Dictionary – Dictionary, DictionaryLiteral ‣ Float – Float, Double ‣ Nil – Optional, Selector, Pointer ‣ Integer – Int, UInt, Float, Double ‣ String – String, Character, Selector
  • 9. String interpolation enum Byte: UInt8 { case Zero = 0 case One = 1 } let string = "(Byte.Zero)" // "Byte.Zero" // would be nice let string = "(Byte.Zero)" // "0" 1.0
  • 10. Interpolation convertible extension String /* : StringInterpolationConvertible */ { init(stringInterpolationSegment byte: Byte) { self = "(byte.rawValue)" } } let string = "(Byte.Zero)" // "0" 1.0
  • 12. What are patterns? ‣ Enumeration cases ‣ Single equatable values ‣ Ranges and intervals ‣ Value bindings ‣ Type casts ‣ func ~= <T, U> (lhs: T, rhs: U) -> Bool ‣ Tuples of anything above
  • 13.
  • 14. What are patterns? ‣ Enumeration cases ‣ Single equatable values ‣ Ranges and intervals ‣ Value bindings ‣ Type casts ‣ func ~= <T, U> (lhs: T, rhs: U) -> Bool ‣ Tuples of anything above
  • 15. Where do we use them? ‣ Switch statements ‣ If-let bindings ‣ For-in loops ‣ Catch statements
  • 16. case let point = (1, 2) switch point { case (0, 0): println("origin") default: println("arbitrary point") } 1.0
  • 17. case let where let point = (3, 4) switch point { case let (x, y) where x == y: println("point on x = y line") default: println("arbitrary point") } 1.0
  • 18. if let where let point: (Int, Int)? = maybePoint() if let (_, y) = point where y > 0 { println("point above x axis") } 1.2
  • 19. for in where let points = [ (1, 2), (-3, 4), (5, -6), (-7, -8), (9, 10) ] for (x, y) in points where x > 0 && y > 0 { println("point in 1st quadrant: ((x), (y))") } 1.2
  • 20. if case let point = (5, 6) let (width, height) = ( Int(UIScreen.mainScreen().bounds.width), Int(UIScreen.mainScreen().bounds.height) ) if case (0 ... width, 0 ... height) = point { print("point on screen") } 2.0
  • 21. if case let where let point = (7, 8) if case let (x, 1 ..< Int.max) = point where x < 0 { print("point in 2nd quadrant") } 2.0
  • 22. if case let where switch subject { case pattern where condition: // becomes if case pattern = subject where condition { // multiple cases not yet supported if case pattern1, pattern2 = subject { // compiler error 2.0
  • 23. for case let in where let points: [(Int, Int)?] = maybePoints() for case .Some(let (x, y)) in points where x < 0 && y < 0 { print("point in 3rd quadrant: ((x), (y))") } 2.0
  • 24. for case let in where for element in subject { if case pattern = element where condition { // becomes for case pattern in subject where condition { // multiple cases not yet supported for case pattern1, pattern2 in subject { // compiler error 2.0
  • 26. Default behavior struct Vector { typealias Point = (x: Double, y: Double) let start: Point let end: Point var length: Double { return sqrt(pow(end.x - start.x, 2) + pow(end.y - start.y, 2)) } } let unitVector = Vector(start: (0, 0), end: (1, 1)) 2.0
  • 27. Default behavior 2.0 (.0 0, .1 0) (.0 1, .1 1)
  • 28. Reflection methods ‣ Custom description ‣ Custom children tree ‣ Custom Quick Look preview
  • 29. Custom description extension Vector: CustomStringConvertible { var description: String { return "((start.x) × (start.y)) → ((end.x) × (end.y))" } } 2.0
  • 30. Custom description 2.0 "(0.0 × 0.0) → (1.0 × 1.0)"
  • 31. Custom mirror extension Vector: CustomReflectable { func customMirror() -> Mirror { return Mirror(self, children: [ "start": "(start.x) × (start.y)", "end": "(end.x) × (end.y)", "length": length ]) } } 2.0
  • 32. Custom mirror 2.0 start "0.0 × 0.0" end "1.0 × 1.0" length 1.414213562373095
  • 33. Custom preview extension Vector: CustomPlaygroundQuickLookable { func customPlaygroundQuickLook() -> PlaygroundQuickLook { var bezierPath = UIBezierPath() // draw the path return .BezierPath(bezierPath) } } 2.0
  • 35. Reflection principles ‣ Overrides default type descriptors ‣ Provides rich visualization ‣ Read-only
  • 37. Available bridging methods ‣ Inherit from Objective-C classes ‣ @objc attribute ‣ Bridging headers ‣ …and that’s basically it
  • 38. Or is it? @interface NSArray<Element> : NSObject // objective-c class @end struct Array<Element> { // generic swift struct } let swiftArray: [Int] let objcArray = swiftArray as NSArray // no problem 2.0
  • 39. Or is it? @interface NSArray : NSObject @end struct Array<Element>: _ObjectiveCBridgeable { } let swiftArray: [Int] let objcArray = swiftArray as NSArray 2.0
  • 40. Bridgeable protocol _ObjectiveCBridgeable { typealias _ObjectiveCType static func _isBridgedToObjectiveC() -> Bool static func _getObjectiveCType() -> Any.Type func _bridgeToObjectiveC() -> _ObjectiveCType static func _forceBridgeFromObjectiveC(...) static func _conditionallyBridgeFromObjectiveC(...) } 2.0
  • 41. Bridgeable @interface XYZPoint : NSObject - (instancetype)initWithX:(double)x y:(double)y; @property double x; @property double y; @end struct Point { let x: Double let y: Double } 2.0
  • 42. extension Point: _ObjectiveCBridgeable { typealias _ObjectiveCType = XYZPoint static func _isBridgedToObjectiveC() -> Bool { return true } static func _getObjectiveCType() -> Any.Type { return _ObjectiveCType.self } func _bridgeToObjectiveC() -> _ObjectiveCType { return XYZPoint(x: x, y: y) } static func _forceBridgeFromObjectiveC(source: _ObjectiveCType, inout result: Point?) { result = Point(x: source.x, y: source.y) } static func _conditionallyBridgeFromObjectiveC(source: _ObjectiveCType, inout result: Point?) -> Bool { _forceBridgeFromObjectiveC(source, result: &result) return true } } 2.0
  • 43. Bridgeable let objcPoint = XYZPoint(x: 1, y: 2) if let swiftPoint = objcPoint as? Point { // that's right } let objcPoint = XYZPoint(x: 3, y: 4) let swiftPoint = objcPoint as Point // yeah let swiftPoint = Point(x: 5, y: 6) let objcPoint = swiftPoint as XYZPoint // hell yeah let point: XYZPoint = Point(x: 7, y: 8) // mind: blown 2.0
  • 44. Recap ‣ Literal Convertibles ‣ String Interpolation ‣ Pattern Matching ‣ Reflection ‣ Objective-C Bridging
  • 45. How to learn the gems ‣ Carefully read Xcode release notes ‣ Follow right people on Twitter ‣ Study Swift module interface ‣ Use LLDB type lookup ‣ Experiment in playgrounds