SlideShare a Scribd company logo
1 of 41
Download to read offline
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

Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Arnaud Giuliani
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is hereSebastiano Armeli
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016Manoj Kumar
 
Алексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуляАлексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуляSergey Platonov
 
Reactive, component 그리고 angular2
Reactive, component 그리고  angular2Reactive, component 그리고  angular2
Reactive, component 그리고 angular2Jeado Ko
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015NAVER / MusicPlatform
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsBartosz Kosarzycki
 
How to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftHow to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftGiordano Scalzo
 
Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013aleks-f
 
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.boyney123
 
JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )Victor Verhaagen
 
Functional Reactive Programming with RxJS
Functional Reactive Programming with RxJSFunctional Reactive Programming with RxJS
Functional Reactive Programming with RxJSstefanmayer13
 
10. session 10 loops and arrays
10. session 10   loops and arrays10. session 10   loops and arrays
10. session 10 loops and arraysPhúc Đỗ
 
Planet-HTML5-Game-Engine Javascript Performance Enhancement
Planet-HTML5-Game-Engine Javascript Performance EnhancementPlanet-HTML5-Game-Engine Javascript Performance Enhancement
Planet-HTML5-Game-Engine Javascript Performance Enhancementup2soul
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2zindadili
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsLeonardo Borges
 
Kotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoKotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoArnaud Giuliani
 

What's hot (20)

Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017
 
Day 1
Day 1Day 1
Day 1
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
Алексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуляАлексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуля
 
Reactive, component 그리고 angular2
Reactive, component 그리고  angular2Reactive, component 그리고  angular2
Reactive, component 그리고 angular2
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 
How to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftHow to Clone Flappy Bird in Swift
How to Clone Flappy Bird in Swift
 
Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013
 
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.
 
JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )
 
Scala to assembly
Scala to assemblyScala to assembly
Scala to assembly
 
Functional Reactive Programming with RxJS
Functional Reactive Programming with RxJSFunctional Reactive Programming with RxJS
Functional Reactive Programming with RxJS
 
10. session 10 loops and arrays
10. session 10   loops and arrays10. session 10   loops and arrays
10. session 10 loops and arrays
 
Planet-HTML5-Game-Engine Javascript Performance Enhancement
Planet-HTML5-Game-Engine Javascript Performance EnhancementPlanet-HTML5-Game-Engine Javascript Performance Enhancement
Planet-HTML5-Game-Engine Javascript Performance Enhancement
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event Systems
 
Kotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoKotlin cheat sheet by ekito
Kotlin cheat sheet by ekito
 
Es.next
Es.nextEs.next
Es.next
 

Viewers also liked

Дизайн онлайн-изданий, ориентированный на читателя
Дизайн онлайн-изданий, ориентированный на читателя Дизайн онлайн-изданий, ориентированный на читателя
Дизайн онлайн-изданий, ориентированный на читателя Медведев Маркетинг
 
Effectivepresentations
EffectivepresentationsEffectivepresentations
Effectivepresentationsnailulhafiz
 
Rassegna stampa Legge sprechi alimentari_ Fogliani_agosto 2016
Rassegna stampa Legge sprechi alimentari_ Fogliani_agosto 2016Rassegna stampa Legge sprechi alimentari_ Fogliani_agosto 2016
Rassegna stampa Legge sprechi alimentari_ Fogliani_agosto 2016Gregorio Fogliani
 
7 analisis de tormentas
7 analisis de tormentas7 analisis de tormentas
7 analisis de tormentasJuan Soto
 
Install and Configure Ubuntu for Hadoop Installation for beginners
Install and Configure Ubuntu for Hadoop Installation for beginners Install and Configure Ubuntu for Hadoop Installation for beginners
Install and Configure Ubuntu for Hadoop Installation for beginners Shilpa Hemaraj
 
Exposicion de las rocas
Exposicion de las rocasExposicion de las rocas
Exposicion de las rocasURACCAN
 

Viewers also liked (12)

Eft Testimonials
Eft TestimonialsEft Testimonials
Eft Testimonials
 
Italy
ItalyItaly
Italy
 
լևոն
լևոնլևոն
լևոն
 
Memoria primária
Memoria primáriaMemoria primária
Memoria primária
 
Дизайн онлайн-изданий, ориентированный на читателя
Дизайн онлайн-изданий, ориентированный на читателя Дизайн онлайн-изданий, ориентированный на читателя
Дизайн онлайн-изданий, ориентированный на читателя
 
Artefacto TIC
Artefacto TICArtefacto TIC
Artefacto TIC
 
Effectivepresentations
EffectivepresentationsEffectivepresentations
Effectivepresentations
 
Rassegna stampa Legge sprechi alimentari_ Fogliani_agosto 2016
Rassegna stampa Legge sprechi alimentari_ Fogliani_agosto 2016Rassegna stampa Legge sprechi alimentari_ Fogliani_agosto 2016
Rassegna stampa Legge sprechi alimentari_ Fogliani_agosto 2016
 
7 analisis de tormentas
7 analisis de tormentas7 analisis de tormentas
7 analisis de tormentas
 
Install and Configure Ubuntu for Hadoop Installation for beginners
Install and Configure Ubuntu for Hadoop Installation for beginners Install and Configure Ubuntu for Hadoop Installation for beginners
Install and Configure Ubuntu for Hadoop Installation for beginners
 
Exposicion de las rocas
Exposicion de las rocasExposicion de las rocas
Exposicion de las rocas
 
Internet y derecho fundamentales diapos
Internet y derecho fundamentales diaposInternet y derecho fundamentales diapos
Internet y derecho fundamentales diapos
 

Similar to Swift - One step forward from Obj-C

Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksMongoDB
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScriptAndrew Dupont
 
Hello, Is That FreeSWITCH? Then We're Coming to Check You!
Hello, Is That FreeSWITCH? Then We're Coming to Check You!Hello, Is That FreeSWITCH? Then We're Coming to Check You!
Hello, Is That FreeSWITCH? Then We're Coming to Check You!PVS-Studio
 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptxGuy Komari
 
Protocol Oriented MVVM - Auckland iOS Meetup
Protocol Oriented MVVM - Auckland iOS MeetupProtocol Oriented MVVM - Auckland iOS Meetup
Protocol Oriented MVVM - Auckland iOS MeetupNatasha Murashev
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bitsChris Saylor
 
Minimizing Decision Fatigue to Improve Team Productivity
Minimizing Decision Fatigue to Improve Team ProductivityMinimizing Decision Fatigue to Improve Team Productivity
Minimizing Decision Fatigue to Improve Team ProductivityDerek Lee Boire
 
Front End Development: The Important Parts
Front End Development: The Important PartsFront End Development: The Important Parts
Front End Development: The Important PartsSergey Bolshchikov
 
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftReactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftFlorent Pillet
 
Protocol-Oriented MVVM (extended edition)
Protocol-Oriented MVVM (extended edition)Protocol-Oriented MVVM (extended edition)
Protocol-Oriented MVVM (extended edition)Natasha Murashev
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummaryAmal Khailtash
 
The current program only run one iteration of the KMeans algorithm. .docx
The current program only run one iteration of the KMeans algorithm. .docxThe current program only run one iteration of the KMeans algorithm. .docx
The current program only run one iteration of the KMeans algorithm. .docxtodd241
 
CodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilderCodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilderAndres Almiray
 
What's New In Python 2.6
What's New In Python 2.6What's New In Python 2.6
What's New In Python 2.6Richard Jones
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescriptDavid Furber
 
Scaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with ScalaScaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with ScalaOstap Andrusiv
 

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

Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
 
Protocol-Oriented MVVM
Protocol-Oriented MVVMProtocol-Oriented MVVM
Protocol-Oriented MVVM
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
 
Hello, Is That FreeSWITCH? Then We're Coming to Check You!
Hello, Is That FreeSWITCH? Then We're Coming to Check You!Hello, Is That FreeSWITCH? Then We're Coming to Check You!
Hello, Is That FreeSWITCH? Then We're Coming to Check You!
 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptx
 
Protocol Oriented MVVM - Auckland iOS Meetup
Protocol Oriented MVVM - Auckland iOS MeetupProtocol Oriented MVVM - Auckland iOS Meetup
Protocol Oriented MVVM - Auckland iOS Meetup
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
 
ECMAScript 2015 Tips & Traps
ECMAScript 2015 Tips & TrapsECMAScript 2015 Tips & Traps
ECMAScript 2015 Tips & Traps
 
Minimizing Decision Fatigue to Improve Team Productivity
Minimizing Decision Fatigue to Improve Team ProductivityMinimizing Decision Fatigue to Improve Team Productivity
Minimizing Decision Fatigue to Improve Team Productivity
 
Front End Development: The Important Parts
Front End Development: The Important PartsFront End Development: The Important Parts
Front End Development: The Important Parts
 
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftReactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwift
 
Protocol-Oriented MVVM (extended edition)
Protocol-Oriented MVVM (extended edition)Protocol-Oriented MVVM (extended edition)
Protocol-Oriented MVVM (extended edition)
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
 
Kotlin Coroutines and Rx
Kotlin Coroutines and RxKotlin Coroutines and Rx
Kotlin Coroutines and Rx
 
The current program only run one iteration of the KMeans algorithm. .docx
The current program only run one iteration of the KMeans algorithm. .docxThe current program only run one iteration of the KMeans algorithm. .docx
The current program only run one iteration of the KMeans algorithm. .docx
 
CodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilderCodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilder
 
What's New In Python 2.6
What's New In Python 2.6What's New In Python 2.6
What's New In Python 2.6
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescript
 
Scaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with ScalaScaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with Scala
 

Recently uploaded

%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 Bahrainmasabamasaba
 
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-learnAmarnathKambale
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfayushiqss
 
%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 tembisamasabamasaba
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfryanfarris8
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedDelhi Call girls
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 

Recently uploaded (20)

%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
 
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
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
%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
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 

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
  • 41. Thank You Nissan Tsafrir @ntsafrir nissan@pixandbyte.com