SlideShare a Scribd company logo
Swift - One Step Forward from ObjC 
Nissan Tsafrir // @ntsafrir // { Pix & Byte } 
www.pixandbyte.com
Swift 
Fast . Modern . Safe . Interactive
AGENDA 
Rewrite few familiar Cocoa Touch code examples 
from Obj-C to Swift by learning to use Closures, 
Enums, Switch-Case with Pattern matching and 
more.
Replace complex macros with 
functions or generics
Replace complex macros with functions 
ObjC 
! 
NSLocalizedString(@"OK",@"a comment")
Replace complex macros with functions 
Swift 
! 
NSLocalizedString("OK", comment:"comment")
Replace complex macros with functions 
#define NSLocalizedStringWithDefaultValue(key, tbl, bundle, val, comment)  
[bundle localizedStringForKey:(key) value:(val) table:(tbl)] 
! 
// shorthand macros 
#define NSLocalizedString(key, comment) … 
#define NSLocalizedStringFromTable(key, tbl, comment) … 
!! 
ObjC 
! 
NSLocalizedString(@"OK",@"a comment")
Replace complex macros with functions 
Swift 
! 
// In Foundation Module: 
! 
func NSLocalizedString(key: String, tableName: String? = default, bundle: 
NSBundle = default, value: String = default, #comment: String) -> String 
let str = NSLocalizedString("OK", comment:"comment")
Functions 
- Default parameter values 
- External parameter name used when calling the function 
- Local parameter name available only in the function scope 
- Shorthand external parameter names - #comment 
let strError = NSLocalizedString("OK") // Error 
Type '(String, tableName: String?, bundle: NSBundle, value: String, comment: String)' 
does not conform to protocol 'StringLiteralConvertible' 
let str334 = NSLocalizedString("OK", "") // Error 
func NSLocalizedString(key: String, tableName: String? = default, bundle: 
NSBundle = default, value: String = default, #comment: String) -> String 
# Same external and local param name. 
Useful for global functions
! 
Methods - Functions associated with type 
“Swift gives the first parameter name in a method a local parameter name by 
default, and gives the second and subsequent parameter names both local and 
external parameter names by default.” 
class FooClass { 
func updateText(text: String, color: UIColor) -> String { 
return "(text) color:(color)" 
} 
} 
! 
let fc = FooClass() 
fc.updateText("tlv", UIColor.blueColor()) 
! 
! 
fc.updateText("tlv", color: UIColor.blueColor()) //OK
What you can do with your exiting complex macros 
• Replace the macros with C functions 
• Create ObjC wrapper class to implement/use the macros as 
functions. 
• Use Swift functions with defaults
Closure 
"Function closures capture local state variables! 
(Objects are state data with attached behavior;! 
Closures are behaviors with attached state data! 
and without the overhead of classes.)"! 
! 
Peter Norvig
ObjC - Blocks 
__block NSNumber *someVal = @10; // strong and mutable 
__weak typeof(self) weakSelf = self; 
! 
[locationManager getCurrentLocationWithCompletion:^(CLLocation *location) { 
if (!location) { 
return; 
} 
! 
if (weakSelf.completionBlock) { // Safer to use strongSelf in here 
weakSelf.completionBlock(location); 
} 
someVal = @20; 
}]; 
!
ObjC - Blocks 
! 
typedef void(^ PBUpdateLocationCompletion)(CLLocation * location); 
! 
@property (copy, nonatomic) PBUpdateLocationCompletion completionBlock;
var successHandler : ((feed: Array) -> ())? 
var someValue = 1 
! 
successHandler = { feed in 
self.refreshFeed(feed) 
someValue = 2 
} 
Swift - Closure
request.successHandler = { [unowned self] feed in 
self.refreshFeed(feed) 
} 
Capture List
Closure Factory Method 
Image Filter Example 
func blurFilter(radius: Int) -> (image: UIImage) -> (UIImage) { 
return { image in 
return BlurImage(image, radius) 
} 
} 
! 
let blur20 = blurFilter(20) 
! 
let blurredImage = blur20(image)
Replace Delegate with Closures
class AddViewController : UIViewController { 
var didCancel : ((AddViewController) -> ())? 
var didFinish : ((AddViewController, name: String) -> ())? 
} 
class AddViewController : UIViewController { 
typealias CancelHandler = (AddViewController) -> () 
typealias FinishHandler = (AddViewController, name: String) -> () 
var didCancel : CancelHandler? 
var didFinish : FinishHandler? 
} 
Replace Delegate with Closures
if let addVC = navigationVC.topViewController as? AddViewController { 
! 
addVC.didCancel = { controller in 
self.dismissViewControllerAnimated(true, completion: nil) 
} 
addVC.didFinish = { controller, name in 
self.dismissViewControllerAnimated(true, completion: nil) 
self.addObjectWithName(name) 
} 
} 
Delegate with Closures
Replace if -isEqual-else with 
switch-case and pattern matching
Replace if-isEqual-else with switch-case and pattern matching 
if ([segue.identifier isEqualToString:@"showDetails"]) { 
//… 
} else if ([segue.identifier isEqualToString:"add"]) { 
//… 
} 
ObjC
Replace if-isEqual-else with switch-case and pattern matching 
override func prepareForSegue(segue: UIStoryboardSegue, sender: …) { 
if segue.identifier == "showDetail" { 
//... 
} else if segue.identifier == "add" { 
//.. 
} 
} 
Swift
Replace if-isEqual-else with switch-case and pattern matching 
override func prepareForSegue(segue: UIStoryboardSegue, sender: …) { 
switch segue.identifier { 
case "showDetail": 
//… 
case "add": 
//… 
default: break 
} 
} 
Swift 
Switches support any kind of data and a wide variety of comparison 
operations.
if let nvc = segue.destinationViewController as? UINavigationController { 
… 
} 
Replace if-isEqual-else with switch-case and pattern matching 
Optional binding that use optional down casting 
“Try to access viewController as a navigation controller. If this is 
successful, set a new temporary constant called nvc to the value 
stored in the returned optional UINavigationController.”
Replace if-isEqual-else with switch-case and pattern matching 
Another switch case pattern matching example 
override func prepareForSegue(segue: UIStoryboardSegue, sender: … 
{ 
switch segue.destinationViewController { 
case let nvc as UINavigationController: 
… 
case let dvc as DetailsViewController: 
… 
default: break 
} 
}
Error Reporting
Results Enumeration and associated value 
With NSErrorPointer (NSError?) 
var error : NSError? 
let url = NSURL(string: "http://www.apple.com") 
let data = NSData(contentsOfURL: url, 
options: NSDataReadingOptions.allZeros, 
error: &error) 
! 
if let anError = error { 
println("failure: (anErrror.localizedDescription())"  ) 
}
Results Enumeration and associated value 
Using Enums with associated value 
enum ServerResult { 
case Result (NSData) 
case Error (NSError) 
} 
! 
let success = ServerResult.Result(data) 
! 
let failure = ServerResult.Error(NSError(domain: "MyErrorDomain", code: 1, 
userInfo: nil)) 
switch success { 
case let .Result(data): 
let serverResponse = "Received data (data)" 
case let .Error(error): 
let serverResponse = "Failure... (error)" 
}
Setting Defaults with ?? operator
Setting Defaults with ?? operator 
ObjC 
!! 
NSString *name = text ? text : "default-name"; 
Swift 
var text : String? 
… 
! 
! 
let name = text ?? "default-name";
CoreFoundation and other C API 
Get free ARC!
Swift compiler gives CoreFoundation, 
CoreGraphics and others ARC 
/* Shape */ 
let pathRef = CGPathCreateMutable() 
CGPathMoveToPoint(pathRef, nil, 0, 0) 
CGPathAddLineToPoint(pathRef, nil, 400, 0) 
CGPathAddLineToPoint(pathRef, nil, 400, 320) 
CGPathAddLineToPoint(pathRef, nil, 0, 320) 
CGPathAddLineToPoint(pathRef, nil, 0, 0) 
CGPathCloseSubpath(pathRef) 
!! 
// Compiler take care memory management in most cases 
So no need for these: 
CGPathRelease (pathRef) or CFRelease(pathRef)
// In C 
! 
CoreGraphic Structs 
CGRectMake(0, 0, 320, 480) 
! 
// In swift - much more readable 
! 
CGRect(x: 0, y: 0, width: 400, height: 320)
GCD a bit more cleaner
GCD a bit more cleaner 
let group = dispatch_group_create() 
dispatch_group_enter(group) 
dispatch_group_leave(group) 
dispatch_group_notify(group,dispatch_get_main_queue()) { 
… 
} 
! 
dispatch_async(dispatch_get_main_queue()) { 
// trailing closure body 
} 
Type inferred, trailing closure
Singleton : Replace dispatch_once with inner 
struct
Singleton 
You can use dispatch_once but we hope for better way 
class Singleton : NSObject { 
class var sharedInstance : Singleton { 
struct Static { 
static var onceToken : dispatch_once_t = 0 
static var instance : Singleton? = nil 
} 
dispatch_once(&Static.onceToken) { 
Static.instance = Singleton() 
} 
return Static.instance! 
} 
override init() { 
println("yay"); 
} 
} 
! 
Singleton.sharedInstance
Singleton: Replace dispatch_once with inner 
struct 
Class variable currently not supported (xcode 6 beta 7) 
But structs do support static constants 
class Singleton : NSObject { 
class var sharedInstance : Singleton { 
struct Static { 
static let instance : Singleton = Singleton() 
} 
return Static.instance 
} 
override init() { 
println("yay"); 
} 
} 
Follow https://github.com/hpique/SwiftSingleton for updates
References 
! 
- Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/il/jEUH0.l 
- Apple Inc. “Using Swift with Cocoa and Objective-C.” iBooks. https://itun.es/il/1u3-0.l 
- WWDC 14 Swift videos (https://developer.apple.com/videos/wwdc/2014/) 
- Apple’s Dev Forums 
- https://github.com/hpique/SwiftSingleton
Thank You 
Nissan Tsafrir 
@ntsafrir 
nissan@pixandbyte.com

More Related Content

What's hot (20)

PDF
Develop your next app with kotlin @ AndroidMakersFr 2017
Arnaud Giuliani
 
ZIP
Day 1
Pat Zearfoss
 
PDF
EcmaScript 6 - The future is here
Sebastiano Armeli
 
ODP
ES6 PPT FOR 2016
Manoj Kumar
 
PPTX
Алексей Кутумов, Вектор с нуля
Sergey Platonov
 
PDF
Reactive, component 그리고 angular2
Jeado Ko
 
PDF
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
NAVER / MusicPlatform
 
PDF
Kotlin Developer Starter in Android projects
Bartosz Kosarzycki
 
PDF
How to Clone Flappy Bird in Swift
Giordano Scalzo
 
PDF
Dynamic C++ ACCU 2013
aleks-f
 
PDF
Introduction into ES6 JavaScript.
boyney123
 
PDF
JavaScript introduction 1 ( Variables And Values )
Victor Verhaagen
 
PDF
Scala to assembly
Jarek Ratajski
 
PPTX
Functional Reactive Programming with RxJS
stefanmayer13
 
PPTX
10. session 10 loops and arrays
Phúc Đỗ
 
PDF
Planet-HTML5-Game-Engine Javascript Performance Enhancement
up2soul
 
PPTX
Operator overloading2
zindadili
 
PDF
Functional Reactive Programming / Compositional Event Systems
Leonardo Borges
 
PDF
Kotlin cheat sheet by ekito
Arnaud Giuliani
 
PDF
Es.next
kevinsson
 
Develop your next app with kotlin @ AndroidMakersFr 2017
Arnaud Giuliani
 
EcmaScript 6 - The future is here
Sebastiano Armeli
 
ES6 PPT FOR 2016
Manoj Kumar
 
Алексей Кутумов, Вектор с нуля
Sergey Platonov
 
Reactive, component 그리고 angular2
Jeado Ko
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
NAVER / MusicPlatform
 
Kotlin Developer Starter in Android projects
Bartosz Kosarzycki
 
How to Clone Flappy Bird in Swift
Giordano Scalzo
 
Dynamic C++ ACCU 2013
aleks-f
 
Introduction into ES6 JavaScript.
boyney123
 
JavaScript introduction 1 ( Variables And Values )
Victor Verhaagen
 
Scala to assembly
Jarek Ratajski
 
Functional Reactive Programming with RxJS
stefanmayer13
 
10. session 10 loops and arrays
Phúc Đỗ
 
Planet-HTML5-Game-Engine Javascript Performance Enhancement
up2soul
 
Operator overloading2
zindadili
 
Functional Reactive Programming / Compositional Event Systems
Leonardo Borges
 
Kotlin cheat sheet by ekito
Arnaud Giuliani
 
Es.next
kevinsson
 

Viewers also liked (12)

DOCX
Eft Testimonials
Maxpromotion
 
PPTX
Italy
Matt Beat
 
PPT
լևոն
Meri Grigoryan
 
PPTX
Memoria primária
Carlos Pereira
 
PDF
Дизайн онлайн-изданий, ориентированный на читателя
Медведев Маркетинг
 
PDF
Artefacto TIC
Oreto Benavent
 
PPT
Effectivepresentations
nailulhafiz
 
PDF
Rassegna stampa Legge sprechi alimentari_ Fogliani_agosto 2016
Gregorio Fogliani
 
PPTX
7 analisis de tormentas
Juan Soto
 
PDF
Install and Configure Ubuntu for Hadoop Installation for beginners
Shilpa Hemaraj
 
PPTX
Exposicion de las rocas
URACCAN
 
PPTX
Internet y derecho fundamentales diapos
JOSHEP RODRIGO CAYO HUAYHUA
 
Eft Testimonials
Maxpromotion
 
Italy
Matt Beat
 
լևոն
Meri Grigoryan
 
Memoria primária
Carlos Pereira
 
Дизайн онлайн-изданий, ориентированный на читателя
Медведев Маркетинг
 
Artefacto TIC
Oreto Benavent
 
Effectivepresentations
nailulhafiz
 
Rassegna stampa Legge sprechi alimentari_ Fogliani_agosto 2016
Gregorio Fogliani
 
7 analisis de tormentas
Juan Soto
 
Install and Configure Ubuntu for Hadoop Installation for beginners
Shilpa Hemaraj
 
Exposicion de las rocas
URACCAN
 
Internet y derecho fundamentales diapos
JOSHEP RODRIGO CAYO HUAYHUA
 
Ad

Similar to Swift - One step forward from Obj-C (20)

PPT
Sqlapi0.1
jitendral
 
PDF
Protocol-Oriented MVVM
Natasha Murashev
 
PDF
Fun Teaching MongoDB New Tricks
MongoDB
 
PDF
Writing Maintainable JavaScript
Andrew Dupont
 
PDF
Hello, Is That FreeSWITCH? Then We're Coming to Check You!
PVS-Studio
 
PPTX
golang_getting_started.pptx
Guy Komari
 
PDF
Protocol Oriented MVVM - Auckland iOS Meetup
Natasha Murashev
 
PDF
Javascript: the important bits
Chris Saylor
 
PDF
ECMAScript 2015 Tips & Traps
Adrian-Tudor Panescu
 
PDF
Minimizing Decision Fatigue to Improve Team Productivity
Derek Lee
 
PDF
Front End Development: The Important Parts
Sergey Bolshchikov
 
PDF
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
João Esperancinha
 
PDF
Reactive Programming Patterns with RxSwift
Florent Pillet
 
PDF
Protocol-Oriented MVVM (extended edition)
Natasha Murashev
 
PPT
SystemVerilog OOP Ovm Features Summary
Amal Khailtash
 
PPTX
Kotlin Coroutines and Rx
Shaul Rosenzwieg
 
PDF
L5, Loop and iteration, CSE 202, BN11.pdf
SauravBarua11
 
DOCX
The current program only run one iteration of the KMeans algorithm. .docx
todd241
 
PPT
CodeMash - Building Rich Apps with Groovy SwingBuilder
Andres Almiray
 
KEY
What's New In Python 2.6
Richard Jones
 
Sqlapi0.1
jitendral
 
Protocol-Oriented MVVM
Natasha Murashev
 
Fun Teaching MongoDB New Tricks
MongoDB
 
Writing Maintainable JavaScript
Andrew Dupont
 
Hello, Is That FreeSWITCH? Then We're Coming to Check You!
PVS-Studio
 
golang_getting_started.pptx
Guy Komari
 
Protocol Oriented MVVM - Auckland iOS Meetup
Natasha Murashev
 
Javascript: the important bits
Chris Saylor
 
ECMAScript 2015 Tips & Traps
Adrian-Tudor Panescu
 
Minimizing Decision Fatigue to Improve Team Productivity
Derek Lee
 
Front End Development: The Important Parts
Sergey Bolshchikov
 
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
João Esperancinha
 
Reactive Programming Patterns with RxSwift
Florent Pillet
 
Protocol-Oriented MVVM (extended edition)
Natasha Murashev
 
SystemVerilog OOP Ovm Features Summary
Amal Khailtash
 
Kotlin Coroutines and Rx
Shaul Rosenzwieg
 
L5, Loop and iteration, CSE 202, BN11.pdf
SauravBarua11
 
The current program only run one iteration of the KMeans algorithm. .docx
todd241
 
CodeMash - Building Rich Apps with Groovy SwingBuilder
Andres Almiray
 
What's New In Python 2.6
Richard Jones
 
Ad

Recently uploaded (20)

PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
PDF
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PDF
Online Queue Management System for Public Service Offices in Nepal [Focused i...
Rishab Acharya
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PDF
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
PDF
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PDF
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
PPTX
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
PDF
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PDF
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
Online Queue Management System for Public Service Offices in Nepal [Focused i...
Rishab Acharya
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
Tally software_Introduction_Presentation
AditiBansal54083
 
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 

Swift - One step forward from Obj-C

  • 1. Swift - One Step Forward from ObjC Nissan Tsafrir // @ntsafrir // { Pix & Byte } www.pixandbyte.com
  • 2. Swift Fast . Modern . Safe . Interactive
  • 3. AGENDA Rewrite few familiar Cocoa Touch code examples from Obj-C to Swift by learning to use Closures, Enums, Switch-Case with Pattern matching and more.
  • 4. Replace complex macros with functions or generics
  • 5. Replace complex macros with functions ObjC ! NSLocalizedString(@"OK",@"a comment")
  • 6. Replace complex macros with functions Swift ! NSLocalizedString("OK", comment:"comment")
  • 7. Replace complex macros with functions #define NSLocalizedStringWithDefaultValue(key, tbl, bundle, val, comment) [bundle localizedStringForKey:(key) value:(val) table:(tbl)] ! // shorthand macros #define NSLocalizedString(key, comment) … #define NSLocalizedStringFromTable(key, tbl, comment) … !! ObjC ! NSLocalizedString(@"OK",@"a comment")
  • 8. Replace complex macros with functions Swift ! // In Foundation Module: ! func NSLocalizedString(key: String, tableName: String? = default, bundle: NSBundle = default, value: String = default, #comment: String) -> String let str = NSLocalizedString("OK", comment:"comment")
  • 9. Functions - Default parameter values - External parameter name used when calling the function - Local parameter name available only in the function scope - Shorthand external parameter names - #comment let strError = NSLocalizedString("OK") // Error Type '(String, tableName: String?, bundle: NSBundle, value: String, comment: String)' does not conform to protocol 'StringLiteralConvertible' let str334 = NSLocalizedString("OK", "") // Error func NSLocalizedString(key: String, tableName: String? = default, bundle: NSBundle = default, value: String = default, #comment: String) -> String # Same external and local param name. Useful for global functions
  • 10. ! Methods - Functions associated with type “Swift gives the first parameter name in a method a local parameter name by default, and gives the second and subsequent parameter names both local and external parameter names by default.” class FooClass { func updateText(text: String, color: UIColor) -> String { return "(text) color:(color)" } } ! let fc = FooClass() fc.updateText("tlv", UIColor.blueColor()) ! ! fc.updateText("tlv", color: UIColor.blueColor()) //OK
  • 11. What you can do with your exiting complex macros • Replace the macros with C functions • Create ObjC wrapper class to implement/use the macros as functions. • Use Swift functions with defaults
  • 12. Closure "Function closures capture local state variables! (Objects are state data with attached behavior;! Closures are behaviors with attached state data! and without the overhead of classes.)"! ! Peter Norvig
  • 13. ObjC - Blocks __block NSNumber *someVal = @10; // strong and mutable __weak typeof(self) weakSelf = self; ! [locationManager getCurrentLocationWithCompletion:^(CLLocation *location) { if (!location) { return; } ! if (weakSelf.completionBlock) { // Safer to use strongSelf in here weakSelf.completionBlock(location); } someVal = @20; }]; !
  • 14. ObjC - Blocks ! typedef void(^ PBUpdateLocationCompletion)(CLLocation * location); ! @property (copy, nonatomic) PBUpdateLocationCompletion completionBlock;
  • 15. var successHandler : ((feed: Array) -> ())? var someValue = 1 ! successHandler = { feed in self.refreshFeed(feed) someValue = 2 } Swift - Closure
  • 16. request.successHandler = { [unowned self] feed in self.refreshFeed(feed) } Capture List
  • 17. Closure Factory Method Image Filter Example func blurFilter(radius: Int) -> (image: UIImage) -> (UIImage) { return { image in return BlurImage(image, radius) } } ! let blur20 = blurFilter(20) ! let blurredImage = blur20(image)
  • 19. class AddViewController : UIViewController { var didCancel : ((AddViewController) -> ())? var didFinish : ((AddViewController, name: String) -> ())? } class AddViewController : UIViewController { typealias CancelHandler = (AddViewController) -> () typealias FinishHandler = (AddViewController, name: String) -> () var didCancel : CancelHandler? var didFinish : FinishHandler? } Replace Delegate with Closures
  • 20. if let addVC = navigationVC.topViewController as? AddViewController { ! addVC.didCancel = { controller in self.dismissViewControllerAnimated(true, completion: nil) } addVC.didFinish = { controller, name in self.dismissViewControllerAnimated(true, completion: nil) self.addObjectWithName(name) } } Delegate with Closures
  • 21. Replace if -isEqual-else with switch-case and pattern matching
  • 22. Replace if-isEqual-else with switch-case and pattern matching if ([segue.identifier isEqualToString:@"showDetails"]) { //… } else if ([segue.identifier isEqualToString:"add"]) { //… } ObjC
  • 23. Replace if-isEqual-else with switch-case and pattern matching override func prepareForSegue(segue: UIStoryboardSegue, sender: …) { if segue.identifier == "showDetail" { //... } else if segue.identifier == "add" { //.. } } Swift
  • 24. Replace if-isEqual-else with switch-case and pattern matching override func prepareForSegue(segue: UIStoryboardSegue, sender: …) { switch segue.identifier { case "showDetail": //… case "add": //… default: break } } Swift Switches support any kind of data and a wide variety of comparison operations.
  • 25. if let nvc = segue.destinationViewController as? UINavigationController { … } Replace if-isEqual-else with switch-case and pattern matching Optional binding that use optional down casting “Try to access viewController as a navigation controller. If this is successful, set a new temporary constant called nvc to the value stored in the returned optional UINavigationController.”
  • 26. Replace if-isEqual-else with switch-case and pattern matching Another switch case pattern matching example override func prepareForSegue(segue: UIStoryboardSegue, sender: … { switch segue.destinationViewController { case let nvc as UINavigationController: … case let dvc as DetailsViewController: … default: break } }
  • 28. Results Enumeration and associated value With NSErrorPointer (NSError?) var error : NSError? let url = NSURL(string: "http://www.apple.com") let data = NSData(contentsOfURL: url, options: NSDataReadingOptions.allZeros, error: &error) ! if let anError = error { println("failure: (anErrror.localizedDescription())" ) }
  • 29. Results Enumeration and associated value Using Enums with associated value enum ServerResult { case Result (NSData) case Error (NSError) } ! let success = ServerResult.Result(data) ! let failure = ServerResult.Error(NSError(domain: "MyErrorDomain", code: 1, userInfo: nil)) switch success { case let .Result(data): let serverResponse = "Received data (data)" case let .Error(error): let serverResponse = "Failure... (error)" }
  • 30. Setting Defaults with ?? operator
  • 31. Setting Defaults with ?? operator ObjC !! NSString *name = text ? text : "default-name"; Swift var text : String? … ! ! let name = text ?? "default-name";
  • 32. CoreFoundation and other C API Get free ARC!
  • 33. Swift compiler gives CoreFoundation, CoreGraphics and others ARC /* Shape */ let pathRef = CGPathCreateMutable() CGPathMoveToPoint(pathRef, nil, 0, 0) CGPathAddLineToPoint(pathRef, nil, 400, 0) CGPathAddLineToPoint(pathRef, nil, 400, 320) CGPathAddLineToPoint(pathRef, nil, 0, 320) CGPathAddLineToPoint(pathRef, nil, 0, 0) CGPathCloseSubpath(pathRef) !! // Compiler take care memory management in most cases So no need for these: CGPathRelease (pathRef) or CFRelease(pathRef)
  • 34. // In C ! CoreGraphic Structs CGRectMake(0, 0, 320, 480) ! // In swift - much more readable ! CGRect(x: 0, y: 0, width: 400, height: 320)
  • 35. GCD a bit more cleaner
  • 36. GCD a bit more cleaner let group = dispatch_group_create() dispatch_group_enter(group) dispatch_group_leave(group) dispatch_group_notify(group,dispatch_get_main_queue()) { … } ! dispatch_async(dispatch_get_main_queue()) { // trailing closure body } Type inferred, trailing closure
  • 37. Singleton : Replace dispatch_once with inner struct
  • 38. Singleton You can use dispatch_once but we hope for better way class Singleton : NSObject { class var sharedInstance : Singleton { struct Static { static var onceToken : dispatch_once_t = 0 static var instance : Singleton? = nil } dispatch_once(&Static.onceToken) { Static.instance = Singleton() } return Static.instance! } override init() { println("yay"); } } ! Singleton.sharedInstance
  • 39. Singleton: Replace dispatch_once with inner struct Class variable currently not supported (xcode 6 beta 7) But structs do support static constants class Singleton : NSObject { class var sharedInstance : Singleton { struct Static { static let instance : Singleton = Singleton() } return Static.instance } override init() { println("yay"); } } Follow https://github.com/hpique/SwiftSingleton for updates
  • 40. References ! - Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/il/jEUH0.l - Apple Inc. “Using Swift with Cocoa and Objective-C.” iBooks. https://itun.es/il/1u3-0.l - WWDC 14 Swift videos (https://developer.apple.com/videos/wwdc/2014/) - Apple’s Dev Forums - https://github.com/hpique/SwiftSingleton