SlideShare a Scribd company logo
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
Hidden Gems in Swift
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

More Related Content

What's hot (20)

PDF
Developer Experience i TypeScript. Najbardziej ikoniczne duo
The Software House
 
PDF
Model-Driven Software Development - Static Analysis & Error Checking
Eelco Visser
 
PDF
C++ L11-Polymorphism
Mohammad Shaker
 
PDF
Variables, expressions, standard types
Rubizza
 
PDF
RESTful API using scalaz (3)
Yeshwanth Kumar
 
DOC
Oops lab manual2
Mouna Guru
 
PDF
Swift で JavaScript 始めませんか? #iOSDC
Tomohiro Kumagai
 
PPTX
Chapter 7 functions (c)
hhliu
 
PPSX
DIWE - Working with MySQL Databases
Rasan Samarasinghe
 
PDF
C++ L08-Classes Part1
Mohammad Shaker
 
PPT
Collection v3
Sunil OS
 
PDF
7 Habits For a More Functional Swift
Jason Larsen
 
PDF
Standford 2015 week9
彼得潘 Pan
 
PPTX
Type Driven Development with TypeScript
Garth Gilmour
 
PDF
Let the type system be your friend
The Software House
 
PDF
Bind me if you can
Ovidiu Farauanu
 
PDF
Standford 2015 week3: Objective-C Compatibility, Property List, Views
彼得潘 Pan
 
PDF
Dynamic C++ ACCU 2013
aleks-f
 
KEY
Objective-Cひとめぐり
Kenji Kinukawa
 
PDF
Property-based testing
Dmitriy Morozov
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
The Software House
 
Model-Driven Software Development - Static Analysis & Error Checking
Eelco Visser
 
C++ L11-Polymorphism
Mohammad Shaker
 
Variables, expressions, standard types
Rubizza
 
RESTful API using scalaz (3)
Yeshwanth Kumar
 
Oops lab manual2
Mouna Guru
 
Swift で JavaScript 始めませんか? #iOSDC
Tomohiro Kumagai
 
Chapter 7 functions (c)
hhliu
 
DIWE - Working with MySQL Databases
Rasan Samarasinghe
 
C++ L08-Classes Part1
Mohammad Shaker
 
Collection v3
Sunil OS
 
7 Habits For a More Functional Swift
Jason Larsen
 
Standford 2015 week9
彼得潘 Pan
 
Type Driven Development with TypeScript
Garth Gilmour
 
Let the type system be your friend
The Software House
 
Bind me if you can
Ovidiu Farauanu
 
Standford 2015 week3: Objective-C Compatibility, Property List, Views
彼得潘 Pan
 
Dynamic C++ ACCU 2013
aleks-f
 
Objective-Cひとめぐり
Kenji Kinukawa
 
Property-based testing
Dmitriy Morozov
 

Viewers also liked (8)

PPTX
Strategia w Social Media w 6 krokach
Filip Cieslak
 
PDF
KISS Augmented Reality
Netguru
 
PDF
Why Would A Programmer Fall In Love With SPA?
Netguru
 
PDF
Payments integration: Stripe & Taxamo
Netguru
 
PPT
Blogi w firmie
Netguru
 
PDF
Czy Project Manger Musi Być Osobą Techniczną?
Netguru
 
PDF
301 Adam Zygadlewicz
ecommerce poland expo
 
PDF
Rozwijanie firmy web developerskiej - Kuba Filipowski, Wiktor Schmidt, Netguru
Biznes 2.0
 
Strategia w Social Media w 6 krokach
Filip Cieslak
 
KISS Augmented Reality
Netguru
 
Why Would A Programmer Fall In Love With SPA?
Netguru
 
Payments integration: Stripe & Taxamo
Netguru
 
Blogi w firmie
Netguru
 
Czy Project Manger Musi Być Osobą Techniczną?
Netguru
 
301 Adam Zygadlewicz
ecommerce poland expo
 
Rozwijanie firmy web developerskiej - Kuba Filipowski, Wiktor Schmidt, Netguru
Biznes 2.0
 
Ad

Similar to Hidden Gems in Swift (20)

PDF
Scala @ TechMeetup Edinburgh
Stuart Roebuck
 
PDF
Coding in Style
scalaconfjp
 
PDF
Idioms in swift 2016 05c
Kaz Yoshikawa
 
PDF
From Java to Scala - advantages and possible risks
SeniorDevOnly
 
PPTX
ES6 Overview
Bruno Scopelliti
 
PPT
SDC - Einführung in Scala
Christian Baranowski
 
PDF
The Art Of Readable Code
Baidu, Inc.
 
PDF
(How) can we benefit from adopting scala?
Tomasz Wrobel
 
PDF
L5, Loop and iteration, CSE 202, BN11.pdf
SauravBarua11
 
PDF
The Scala Programming Language
league
 
PPT
Cpp tutorial
Vikas Sharma
 
PDF
The Ring programming language version 1.7 book - Part 48 of 196
Mahmoud Samir Fayed
 
PPT
CppTutorial.ppt
HODZoology3
 
PDF
Scala in Places API
Łukasz Bałamut
 
PPT
Expert JavaScript tricks of the masters
Ara Pehlivanian
 
PPTX
Getting started with ES6
Nitay Neeman
 
PDF
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
PDF
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
PDF
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
PDF
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
Scala @ TechMeetup Edinburgh
Stuart Roebuck
 
Coding in Style
scalaconfjp
 
Idioms in swift 2016 05c
Kaz Yoshikawa
 
From Java to Scala - advantages and possible risks
SeniorDevOnly
 
ES6 Overview
Bruno Scopelliti
 
SDC - Einführung in Scala
Christian Baranowski
 
The Art Of Readable Code
Baidu, Inc.
 
(How) can we benefit from adopting scala?
Tomasz Wrobel
 
L5, Loop and iteration, CSE 202, BN11.pdf
SauravBarua11
 
The Scala Programming Language
league
 
Cpp tutorial
Vikas Sharma
 
The Ring programming language version 1.7 book - Part 48 of 196
Mahmoud Samir Fayed
 
CppTutorial.ppt
HODZoology3
 
Scala in Places API
Łukasz Bałamut
 
Expert JavaScript tricks of the masters
Ara Pehlivanian
 
Getting started with ES6
Nitay Neeman
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
Ad

More from Netguru (20)

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

Recently uploaded (20)

PPTX
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
PPTX
Function & Procedure: Function Vs Procedure in PL/SQL
Shani Tiwari
 
PDF
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
PPTX
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
PPTX
iaas vs paas vs saas :choosing your cloud strategy
CloudlayaTechnology
 
PPTX
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
PDF
ERP Consulting Services and Solutions by Contetra Pvt Ltd
jayjani123
 
PPTX
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PDF
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
PDF
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
PPTX
Get Started with Maestro: Agent, Robot, and Human in Action – Session 5 of 5
klpathrudu
 
PDF
Technical-Careers-Roadmap-in-Software-Market.pdf
Hussein Ali
 
PPTX
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PPTX
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
PDF
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
PPTX
Smart Doctor Appointment Booking option in odoo.pptx
AxisTechnolabs
 
PPTX
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
Function & Procedure: Function Vs Procedure in PL/SQL
Shani Tiwari
 
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
iaas vs paas vs saas :choosing your cloud strategy
CloudlayaTechnology
 
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
ERP Consulting Services and Solutions by Contetra Pvt Ltd
jayjani123
 
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
Get Started with Maestro: Agent, Robot, and Human in Action – Session 5 of 5
klpathrudu
 
Technical-Careers-Roadmap-in-Software-Market.pdf
Hussein Ali
 
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
Smart Doctor Appointment Booking option in odoo.pptx
AxisTechnolabs
 
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 

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
  • 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