SlideShare ist ein Scribd-Unternehmen logo
1 von 27
Downloaden Sie, um offline zu lesen
LET’S MIGRATE TO 3.0
COCOAHEADS NANTES
David Bonnet - @iGranDav
19 January 2017
A LITTLE BIT OF HISTORY…
▸ From Swift 1.x to Swift 2.x
▸ Just remember ErrorType and throwable types
▸ Swift 3.0 is the first community version !
🎉 "
‣ it also breaks code ! 😅
⚠
STILL NOT ABI STABLE !
Everything needs to be migrated
LET’S DO IT SOFTLYSWIFT 2.3
LET’S DO IT SOFTLY - SWIFT 2.3
A LIGHTWEIGHT UPDATE
▸ Only takes advantage of Nullability Checking on Objective-C Interoperability
// Swift 2.2
let image = CIImage(MTLTexture: texture, options: options)
let extent = image.extent // this code can lead to a crash
// Swift 3.0
if let image = CIImage(MTLTexture: texture, options: options) {
…
}
▸ This can help you migrate quickly to the SDK 10 on a big base code %
5
LET’S DO IT SOFTLY - SWIFT 2.3
A TEMPORARY SOLUTION
▸ Xcode loses code sense (even more than usual)
▸ Sometimes completion code is absent / No code coloration when lost
▸ When showing real-time errors in source code, Xcode can get lost
▸ this is valid swift 2.3 code ! and it builds 🤕
▸ fixed in latest Xcode 8.2.1
▸ Xcode 8.2.x is the last version to support it! 😈
6
OK NOW FOR REALSWIFT 3.0
APPLE SOLUTION
LET’S MIGRATE - SWIFT 3.0
LET’S MIGRATE - SWIFT 3.0
APPLE SOLUTION - MIGRATION ASSISTANT
9
LET’S MIGRATE - SWIFT 3.0
APPLE SOLUTION - MIGRATION ASSISTANT IN REAL LIFE
10
😱 Using Xcode 8.0
AN APPROACH
LET’S MIGRATE - SWIFT 3.0
LET’S MIGRATE - SWIFT 3.0
1. MIGRATE YOUR DEPENDENCIES - COCOAPODS / CARTHAGE
▸ Long live Objective-C! 👻
▸ Almost nothing to do here…
▸ Some authors have annotated their libraries: better swift interoperability!
▸ Others have created a brand new swift version:
▸ MMDrawerController has been converted to DrawerController
drawerController?.openDrawerGestureModeMask = MMOpenDrawerGestureMode.None
[X] ’None' has been renamed to 'none'
12
https://github.com/mutualmobile/MMDrawerController/issues/476
drawerController?.openDrawerGestureModeMask = MMOpenDrawerGestureMode.none
[X] 'none' is unavailable: use [] to construct an empty option set
LET’S MIGRATE - SWIFT 3.0
1. MIGRATE YOUR DEPENDENCIES - COCOAPODS / CARTHAGE
▸ ⚠ update your libraries means update also their APIs or introduce new features!
extension Results {
func toArray() -> [T] {
return self.map {$0}
}
}
extension RealmSwift.List {
func toArray() -> [T] {
return self.map {$0}
}
}
13
=>
//New definition in RxRealm
extension List: NotificationEmitter {
public typealias ElementType = Element
public func toArray() -> [Element] {
return Array(self)
}
}
14
▸ Migrate your code template before the migration!
▸ SwiftGen - https://github.com/AliSoftware/SwiftGen
-t swift3
LET’S MIGRATE - SWIFT 3.0
2. USING A CODE GENERATOR?
#!/bin/sh
swiftgen strings
15
▸ Use a linter? Disable it during the migration.
▸ SwiftLint - https://github.com/realm/SwiftLint
1. Launch the migration assistant on your targets only
2. Analyse each source file:
1. Fix it if needed 😅
2. Uncheck from migration when it’s a third party file 😓
3. Do not hesitate to pass the migrator several times
LET’S MIGRATE - SWIFT 3.0
3. SOME OTHER THINGS
REAL WORLD PROBLEMSSHARING ISSUES AND FIXING THEM +
17
▸ To avoid renaming all your APIs calls:
▸ _ is automatically added, you probably want to name them properly
func updateIdentityWithName(_ name: String, firstname: String) throws
▸ Some Foundation objects with deleted NS prefix are casted to conform to
new APIs
let url = NSURL(string: "http://someurl.com" )
URLComponents(url: url as URL, resolvingAgainstBaseURL: false)
REAL WORLD PROBLEMS
BEWARE SOME CHANGES ARE MADE AUTOMATICALLY
SE-0046
if let url = URL(string: "http://someurl.com" ) {
URLComponents(url: url, resolvingAgainstBaseURL: false)
}
func updateIdentity(name: String, firstname: String) throws
18
▸ A cast to AnyObject is frequently added although new APIs accept Any
▸ Convert your JSON objects to [String: Any]
▸ ⚠ Some types becomes values types!
▸ public struct Date versus open class NSDate
▸ But it can simplify the reading:
▸ (x as NSDate).earlierDate(y) can be changed to x < y ? x : y
REAL WORLD PROBLEMS
BEWARE SOME CHANGES ARE MADE AUTOMATICALLY
https://developer.apple.com/swift/blog/?id=39
19
▸ Your potential if let or guard let on absoluteString will not be
removed, it’s your job 🙂
▸ Tip: If you absolutely need to keep your code block you can use a do
statement
REAL WORLD PROBLEMS
SOME APIS DO NOT RETURN OPTIONALS ANYMORE
open class NSURL {
open var absoluteString: String? { get }
}
public struct URL {
public var absoluteString: String { get }
}
versus
do {
//your code here
}
REAL WORLD PROBLEMS
OPTIONAL COMPARATORS DISAPPEARED
20
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func > <T: Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
21
▸ Dispatch APIs are not correctly migrated (at least at that time using Xcode 8.0)
DispatchQueue.global(qos: .background).async {
//do some work
}
DispatchQueue.global(qos: .default).asyncAfter(deadline: .now() + 1) {
//do some work in 1s from now
}
▸ dispatch_once doesn’t exist anymore 😢
▸ Use lazily initialised globals or static properties 😎
REAL WORLD PROBLEMS
GRAND CENTRAL DISPATCH
SE-0044 & SE-0088
22
▸ Remember Nullability Checking integrated into Swift 2.3
▸ ImplicitlyUnwrappedOptionals are considered like optionals now, but not
all the time 😅
REAL WORLD PROBLEMS
OBJECTIVE-C INTEROPERABILITY
https://www.natashatherobot.com/swift-3-implicitly-unwrapped-optionals/
because File > New Project is a rare thing
func valueUp(value: Int!) {
// oldValue is an Int?
// since value doesn't need to be type checked
let oldValue = value // Int?
// newValue is an Int,
// since value was forced to unwrap
// b/c it had to be type checked to do the addition
let newValue = value + 1 // Int
[…]
}
valueUp(value: 10)
23
▸ Swift 3 renamed a lot of objective-c based APIs automatically "
▸ Legacy swift annotations are still available
▸ nullability / generics
▸ NS_SWIFT_NAME / NS_REFINED_FOR_SWIFT / NS_SWIFT_UNAVAILABLE
▸ New annotations available
▸ NS_NOESCAPE to annotate your objective-c blocks (eg. @noespace)
▸ NSEXTENSIBLESTRING_ENUM to convert a string based obj-c enum to a struct
REAL WORLD PROBLEMS
OBJECTIVE-C INTEROPERABILITY
https://realm.io/news/altconf-nikita-lutsenko-objc-swift-interoperability/
because File > New Project is a rare thing
24
▸ I had to convert manually CGFloat.max to CGFloat.greatestFiniteMagnetude
▸ OptionSet are not converted as expected for default values :
▸ UIControlState() instead of .normal : it works but less readable
▸ Visibility changes : private becomes fileprivate etc…
▸ ⚠ Be aware of open versus public on your libraries
REAL WORLD PROBLEMS
SOME RANDOM NOTES
SE-0067
25
▸ map or flatmap returns LazyCollection types now :
▸ let list = Array(myLazyCollection) if you really need a Collection
▸ New compiler : new warnings like unused results 👾
▸ You can add _ to discard it: _ = foo()
▸ returned result is secondary: @discardableResult on the function can
also avoid this warning
REAL WORLD PROBLEMS
SOME RANDOM NOTES
SE-0067
QUESTION TIMETHANKS FOR YOUR ATTENTION 😀
27
▸ A (mostly) comprehensive list of Swift 3.0 and 2.3 changes
▸ https://buildingvts.com/a-mostly-comprehensive-list-of-swift-3-0-and-2-3-changes-193b904bb5b1
▸ Swift migration guide
▸ https://swift.org/migration-guide/
▸ WWDC 2016 - Session 402 : What’s new in swift
▸ https://developer.apple.com/videos/play/wwdc2016/402/
▸ AltConf - Advanced ObjC <-> Swift Interoperability
▸ https://realm.io/news/altconf-nikita-lutsenko-objc-swift-interoperability/
LET’S MIGRATE TO 3.0
REFERENCES
David Bonnet - @iGranDav
david.bonnet@cocoaheads.fr

Weitere ähnliche Inhalte

Was ist angesagt?

sbt 0.10 for beginners?
sbt 0.10 for beginners?sbt 0.10 for beginners?
sbt 0.10 for beginners?
k4200
 

Was ist angesagt? (20)

Zenly - Reverse geocoding
Zenly - Reverse geocodingZenly - Reverse geocoding
Zenly - Reverse geocoding
 
Create Modern Apps with Android Jetpack
Create Modern Apps with Android JetpackCreate Modern Apps with Android Jetpack
Create Modern Apps with Android Jetpack
 
A little respect for MVC part 1 par Gegoire Lhotellier
A little respect for MVC part 1 par Gegoire LhotellierA little respect for MVC part 1 par Gegoire Lhotellier
A little respect for MVC part 1 par Gegoire Lhotellier
 
CoffeeScript - TechTalk 21/10/2013
CoffeeScript - TechTalk 21/10/2013CoffeeScript - TechTalk 21/10/2013
CoffeeScript - TechTalk 21/10/2013
 
Advanced functional programing in Swift
Advanced functional programing in SwiftAdvanced functional programing in Swift
Advanced functional programing in Swift
 
sbt 0.10 for beginners?
sbt 0.10 for beginners?sbt 0.10 for beginners?
sbt 0.10 for beginners?
 
Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular
 
GraphQL in Symfony
GraphQL in SymfonyGraphQL in Symfony
GraphQL in Symfony
 
webworkers
webworkerswebworkers
webworkers
 
BlaBlaCar et la mise en place d'une fonctionnalité FlagFeature
BlaBlaCar et la mise en place d'une fonctionnalité FlagFeatureBlaBlaCar et la mise en place d'une fonctionnalité FlagFeature
BlaBlaCar et la mise en place d'une fonctionnalité FlagFeature
 
Rethinking Best Practices
Rethinking Best PracticesRethinking Best Practices
Rethinking Best Practices
 
Lifthub (rpscala #31)
Lifthub (rpscala #31)Lifthub (rpscala #31)
Lifthub (rpscala #31)
 
React on es6+
React on es6+React on es6+
React on es6+
 
CocoaHeads Paris - CATransaction: What the flush?!
CocoaHeads Paris - CATransaction: What the flush?!CocoaHeads Paris - CATransaction: What the flush?!
CocoaHeads Paris - CATransaction: What the flush?!
 
JavaScript Web Workers
JavaScript Web WorkersJavaScript Web Workers
JavaScript Web Workers
 
JSAnkara Swift v React Native
JSAnkara Swift v React NativeJSAnkara Swift v React Native
JSAnkara Swift v React Native
 
Tech friday 22.01.2016
Tech friday 22.01.2016Tech friday 22.01.2016
Tech friday 22.01.2016
 
Try Jetpack Compose
Try Jetpack ComposeTry Jetpack Compose
Try Jetpack Compose
 
Couverture de code
Couverture de codeCouverture de code
Couverture de code
 
GDG Kuwait - Modern android development
GDG Kuwait - Modern android developmentGDG Kuwait - Modern android development
GDG Kuwait - Modern android development
 

Andere mochten auch

Andere mochten auch (20)

Build a lego app with CocoaPods
Build a lego app with CocoaPodsBuild a lego app with CocoaPods
Build a lego app with CocoaPods
 
BitTorrent on iOS
BitTorrent on iOSBitTorrent on iOS
BitTorrent on iOS
 
Project Entourage
Project EntourageProject Entourage
Project Entourage
 
CloudKit as a backend
CloudKit as a backendCloudKit as a backend
CloudKit as a backend
 
How to communicate with Smart things?
How to communicate with Smart things?How to communicate with Smart things?
How to communicate with Smart things?
 
Programme MFI retour d'expérience
Programme MFI retour d'expérienceProgramme MFI retour d'expérience
Programme MFI retour d'expérience
 
SwiftyGPIO
SwiftyGPIOSwiftyGPIO
SwiftyGPIO
 
La sécurité sur iOS par Arnaud de Bock
La sécurité sur iOS par Arnaud de BockLa sécurité sur iOS par Arnaud de Bock
La sécurité sur iOS par Arnaud de Bock
 
Quoi de neuf dans iOS 10.3
Quoi de neuf dans iOS 10.3Quoi de neuf dans iOS 10.3
Quoi de neuf dans iOS 10.3
 
Design like a developer
Design like a developerDesign like a developer
Design like a developer
 
Super combinators
Super combinatorsSuper combinators
Super combinators
 
Handle the error
Handle the errorHandle the error
Handle the error
 
Comment faire de HLS votre solution vidéo préférée ?
Comment faire de HLS votre solution vidéo préférée ?Comment faire de HLS votre solution vidéo préférée ?
Comment faire de HLS votre solution vidéo préférée ?
 
Découvrir dtrace en ligne de commande.
Découvrir dtrace en ligne de commande.Découvrir dtrace en ligne de commande.
Découvrir dtrace en ligne de commande.
 
Safari app extensions cleared up by Sanaa Squalli
Safari app extensions cleared up by Sanaa SqualliSafari app extensions cleared up by Sanaa Squalli
Safari app extensions cleared up by Sanaa Squalli
 
Firebase par nicolas lehovetzki
Firebase par nicolas lehovetzkiFirebase par nicolas lehovetzki
Firebase par nicolas lehovetzki
 
Un retour d'expérience sur Apple Pay
Un retour d'expérience sur Apple PayUn retour d'expérience sur Apple Pay
Un retour d'expérience sur Apple Pay
 
J'ai fait une app native en React Native
J'ai fait une app native en React NativeJ'ai fait une app native en React Native
J'ai fait une app native en React Native
 
Alamofire
AlamofireAlamofire
Alamofire
 
Chainable datasource
Chainable datasourceChainable datasource
Chainable datasource
 

Ähnlich wie Let's migrate to Swift 3.0

Google Developer Fest 2010
Google Developer Fest 2010Google Developer Fest 2010
Google Developer Fest 2010
Chris Ramsdale
 
Performance measurement and tuning
Performance measurement and tuningPerformance measurement and tuning
Performance measurement and tuning
AOE
 

Ähnlich wie Let's migrate to Swift 3.0 (20)

JavaScript Modules Past, Present and Future
JavaScript Modules Past, Present and FutureJavaScript Modules Past, Present and Future
JavaScript Modules Past, Present and Future
 
Building Web Apps Sanely - EclipseCon 2010
Building Web Apps Sanely - EclipseCon 2010Building Web Apps Sanely - EclipseCon 2010
Building Web Apps Sanely - EclipseCon 2010
 
KDD 2016 Streaming Analytics Tutorial
KDD 2016 Streaming Analytics TutorialKDD 2016 Streaming Analytics Tutorial
KDD 2016 Streaming Analytics Tutorial
 
Google Developer Fest 2010
Google Developer Fest 2010Google Developer Fest 2010
Google Developer Fest 2010
 
JBoss World 2010
JBoss World 2010JBoss World 2010
JBoss World 2010
 
Making Service Deployments to AWS a breeze with Nova
Making Service Deployments to AWS a breeze with NovaMaking Service Deployments to AWS a breeze with Nova
Making Service Deployments to AWS a breeze with Nova
 
What Makes Objective C Dynamic?
What Makes Objective C Dynamic?What Makes Objective C Dynamic?
What Makes Objective C Dynamic?
 
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!
 
EWD 3 Training Course Part 19: The cache.node APIs
EWD 3 Training Course Part 19: The cache.node APIsEWD 3 Training Course Part 19: The cache.node APIs
EWD 3 Training Course Part 19: The cache.node APIs
 
Typescript tips & tricks
Typescript tips & tricksTypescript tips & tricks
Typescript tips & tricks
 
GumGum: Multi-Region Cassandra in AWS
GumGum: Multi-Region Cassandra in AWSGumGum: Multi-Region Cassandra in AWS
GumGum: Multi-Region Cassandra in AWS
 
Moving from Jenkins 1 to 2 declarative pipeline adventures
Moving from Jenkins 1 to 2 declarative pipeline adventuresMoving from Jenkins 1 to 2 declarative pipeline adventures
Moving from Jenkins 1 to 2 declarative pipeline adventures
 
Advanced Node.JS Meetup
Advanced Node.JS MeetupAdvanced Node.JS Meetup
Advanced Node.JS Meetup
 
Building a Serverless company with Node.js, React and the Serverless Framewor...
Building a Serverless company with Node.js, React and the Serverless Framewor...Building a Serverless company with Node.js, React and the Serverless Framewor...
Building a Serverless company with Node.js, React and the Serverless Framewor...
 
Assembling an Open Source Toolchain to Manage Public, Private and Hybrid Clou...
Assembling an Open Source Toolchain to Manage Public, Private and Hybrid Clou...Assembling an Open Source Toolchain to Manage Public, Private and Hybrid Clou...
Assembling an Open Source Toolchain to Manage Public, Private and Hybrid Clou...
 
Performance measurement and tuning
Performance measurement and tuningPerformance measurement and tuning
Performance measurement and tuning
 
Real-World DevOps — 20 Practical Developers Tips for Tightening Your Operatio...
Real-World DevOps — 20 Practical Developers Tips for Tightening Your Operatio...Real-World DevOps — 20 Practical Developers Tips for Tightening Your Operatio...
Real-World DevOps — 20 Practical Developers Tips for Tightening Your Operatio...
 
Oopp Lab Work
Oopp Lab WorkOopp Lab Work
Oopp Lab Work
 
War between Tools and Design 2016
War between Tools and Design 2016War between Tools and Design 2016
War between Tools and Design 2016
 
K8s in 3h - Kubernetes Fundamentals Training
K8s in 3h - Kubernetes Fundamentals TrainingK8s in 3h - Kubernetes Fundamentals Training
K8s in 3h - Kubernetes Fundamentals Training
 

Mehr von CocoaHeads France

Mehr von CocoaHeads France (8)

Mutation testing for a safer Future
Mutation testing for a safer FutureMutation testing for a safer Future
Mutation testing for a safer Future
 
iOS App Group for Debugging
iOS App Group for DebuggingiOS App Group for Debugging
iOS App Group for Debugging
 
Asynchronous swift
Asynchronous swiftAsynchronous swift
Asynchronous swift
 
Visual accessibility in iOS11
Visual accessibility in iOS11Visual accessibility in iOS11
Visual accessibility in iOS11
 
My script - One year of CocoaHeads
My script - One year of CocoaHeadsMy script - One year of CocoaHeads
My script - One year of CocoaHeads
 
Ui testing dealing with push notifications
Ui testing dealing with push notificationsUi testing dealing with push notifications
Ui testing dealing with push notifications
 
CONTINUOUS DELIVERY WITH FASTLANE
CONTINUOUS DELIVERY WITH FASTLANECONTINUOUS DELIVERY WITH FASTLANE
CONTINUOUS DELIVERY WITH FASTLANE
 
L'intégration continue avec Bitrise
L'intégration continue avec BitriseL'intégration continue avec Bitrise
L'intégration continue avec Bitrise
 

Kürzlich hochgeladen

%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
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
shinachiaurasa2
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 

Kürzlich hochgeladen (20)

%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
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
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
%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
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
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
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 

Let's migrate to Swift 3.0

  • 1. LET’S MIGRATE TO 3.0 COCOAHEADS NANTES David Bonnet - @iGranDav 19 January 2017
  • 2. A LITTLE BIT OF HISTORY… ▸ From Swift 1.x to Swift 2.x ▸ Just remember ErrorType and throwable types ▸ Swift 3.0 is the first community version ! 🎉 " ‣ it also breaks code ! 😅
  • 3. ⚠ STILL NOT ABI STABLE ! Everything needs to be migrated
  • 4. LET’S DO IT SOFTLYSWIFT 2.3
  • 5. LET’S DO IT SOFTLY - SWIFT 2.3 A LIGHTWEIGHT UPDATE ▸ Only takes advantage of Nullability Checking on Objective-C Interoperability // Swift 2.2 let image = CIImage(MTLTexture: texture, options: options) let extent = image.extent // this code can lead to a crash // Swift 3.0 if let image = CIImage(MTLTexture: texture, options: options) { … } ▸ This can help you migrate quickly to the SDK 10 on a big base code % 5
  • 6. LET’S DO IT SOFTLY - SWIFT 2.3 A TEMPORARY SOLUTION ▸ Xcode loses code sense (even more than usual) ▸ Sometimes completion code is absent / No code coloration when lost ▸ When showing real-time errors in source code, Xcode can get lost ▸ this is valid swift 2.3 code ! and it builds 🤕 ▸ fixed in latest Xcode 8.2.1 ▸ Xcode 8.2.x is the last version to support it! 😈 6
  • 7. OK NOW FOR REALSWIFT 3.0
  • 9. LET’S MIGRATE - SWIFT 3.0 APPLE SOLUTION - MIGRATION ASSISTANT 9
  • 10. LET’S MIGRATE - SWIFT 3.0 APPLE SOLUTION - MIGRATION ASSISTANT IN REAL LIFE 10 😱 Using Xcode 8.0
  • 12. LET’S MIGRATE - SWIFT 3.0 1. MIGRATE YOUR DEPENDENCIES - COCOAPODS / CARTHAGE ▸ Long live Objective-C! 👻 ▸ Almost nothing to do here… ▸ Some authors have annotated their libraries: better swift interoperability! ▸ Others have created a brand new swift version: ▸ MMDrawerController has been converted to DrawerController drawerController?.openDrawerGestureModeMask = MMOpenDrawerGestureMode.None [X] ’None' has been renamed to 'none' 12 https://github.com/mutualmobile/MMDrawerController/issues/476 drawerController?.openDrawerGestureModeMask = MMOpenDrawerGestureMode.none [X] 'none' is unavailable: use [] to construct an empty option set
  • 13. LET’S MIGRATE - SWIFT 3.0 1. MIGRATE YOUR DEPENDENCIES - COCOAPODS / CARTHAGE ▸ ⚠ update your libraries means update also their APIs or introduce new features! extension Results { func toArray() -> [T] { return self.map {$0} } } extension RealmSwift.List { func toArray() -> [T] { return self.map {$0} } } 13 => //New definition in RxRealm extension List: NotificationEmitter { public typealias ElementType = Element public func toArray() -> [Element] { return Array(self) } }
  • 14. 14 ▸ Migrate your code template before the migration! ▸ SwiftGen - https://github.com/AliSoftware/SwiftGen -t swift3 LET’S MIGRATE - SWIFT 3.0 2. USING A CODE GENERATOR? #!/bin/sh swiftgen strings
  • 15. 15 ▸ Use a linter? Disable it during the migration. ▸ SwiftLint - https://github.com/realm/SwiftLint 1. Launch the migration assistant on your targets only 2. Analyse each source file: 1. Fix it if needed 😅 2. Uncheck from migration when it’s a third party file 😓 3. Do not hesitate to pass the migrator several times LET’S MIGRATE - SWIFT 3.0 3. SOME OTHER THINGS
  • 16. REAL WORLD PROBLEMSSHARING ISSUES AND FIXING THEM +
  • 17. 17 ▸ To avoid renaming all your APIs calls: ▸ _ is automatically added, you probably want to name them properly func updateIdentityWithName(_ name: String, firstname: String) throws ▸ Some Foundation objects with deleted NS prefix are casted to conform to new APIs let url = NSURL(string: "http://someurl.com" ) URLComponents(url: url as URL, resolvingAgainstBaseURL: false) REAL WORLD PROBLEMS BEWARE SOME CHANGES ARE MADE AUTOMATICALLY SE-0046 if let url = URL(string: "http://someurl.com" ) { URLComponents(url: url, resolvingAgainstBaseURL: false) } func updateIdentity(name: String, firstname: String) throws
  • 18. 18 ▸ A cast to AnyObject is frequently added although new APIs accept Any ▸ Convert your JSON objects to [String: Any] ▸ ⚠ Some types becomes values types! ▸ public struct Date versus open class NSDate ▸ But it can simplify the reading: ▸ (x as NSDate).earlierDate(y) can be changed to x < y ? x : y REAL WORLD PROBLEMS BEWARE SOME CHANGES ARE MADE AUTOMATICALLY https://developer.apple.com/swift/blog/?id=39
  • 19. 19 ▸ Your potential if let or guard let on absoluteString will not be removed, it’s your job 🙂 ▸ Tip: If you absolutely need to keep your code block you can use a do statement REAL WORLD PROBLEMS SOME APIS DO NOT RETURN OPTIONALS ANYMORE open class NSURL { open var absoluteString: String? { get } } public struct URL { public var absoluteString: String { get } } versus do { //your code here }
  • 20. REAL WORLD PROBLEMS OPTIONAL COMPARATORS DISAPPEARED 20 // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func > <T: Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } }
  • 21. 21 ▸ Dispatch APIs are not correctly migrated (at least at that time using Xcode 8.0) DispatchQueue.global(qos: .background).async { //do some work } DispatchQueue.global(qos: .default).asyncAfter(deadline: .now() + 1) { //do some work in 1s from now } ▸ dispatch_once doesn’t exist anymore 😢 ▸ Use lazily initialised globals or static properties 😎 REAL WORLD PROBLEMS GRAND CENTRAL DISPATCH SE-0044 & SE-0088
  • 22. 22 ▸ Remember Nullability Checking integrated into Swift 2.3 ▸ ImplicitlyUnwrappedOptionals are considered like optionals now, but not all the time 😅 REAL WORLD PROBLEMS OBJECTIVE-C INTEROPERABILITY https://www.natashatherobot.com/swift-3-implicitly-unwrapped-optionals/ because File > New Project is a rare thing func valueUp(value: Int!) { // oldValue is an Int? // since value doesn't need to be type checked let oldValue = value // Int? // newValue is an Int, // since value was forced to unwrap // b/c it had to be type checked to do the addition let newValue = value + 1 // Int […] } valueUp(value: 10)
  • 23. 23 ▸ Swift 3 renamed a lot of objective-c based APIs automatically " ▸ Legacy swift annotations are still available ▸ nullability / generics ▸ NS_SWIFT_NAME / NS_REFINED_FOR_SWIFT / NS_SWIFT_UNAVAILABLE ▸ New annotations available ▸ NS_NOESCAPE to annotate your objective-c blocks (eg. @noespace) ▸ NSEXTENSIBLESTRING_ENUM to convert a string based obj-c enum to a struct REAL WORLD PROBLEMS OBJECTIVE-C INTEROPERABILITY https://realm.io/news/altconf-nikita-lutsenko-objc-swift-interoperability/ because File > New Project is a rare thing
  • 24. 24 ▸ I had to convert manually CGFloat.max to CGFloat.greatestFiniteMagnetude ▸ OptionSet are not converted as expected for default values : ▸ UIControlState() instead of .normal : it works but less readable ▸ Visibility changes : private becomes fileprivate etc… ▸ ⚠ Be aware of open versus public on your libraries REAL WORLD PROBLEMS SOME RANDOM NOTES SE-0067
  • 25. 25 ▸ map or flatmap returns LazyCollection types now : ▸ let list = Array(myLazyCollection) if you really need a Collection ▸ New compiler : new warnings like unused results 👾 ▸ You can add _ to discard it: _ = foo() ▸ returned result is secondary: @discardableResult on the function can also avoid this warning REAL WORLD PROBLEMS SOME RANDOM NOTES SE-0067
  • 26. QUESTION TIMETHANKS FOR YOUR ATTENTION 😀
  • 27. 27 ▸ A (mostly) comprehensive list of Swift 3.0 and 2.3 changes ▸ https://buildingvts.com/a-mostly-comprehensive-list-of-swift-3-0-and-2-3-changes-193b904bb5b1 ▸ Swift migration guide ▸ https://swift.org/migration-guide/ ▸ WWDC 2016 - Session 402 : What’s new in swift ▸ https://developer.apple.com/videos/play/wwdc2016/402/ ▸ AltConf - Advanced ObjC <-> Swift Interoperability ▸ https://realm.io/news/altconf-nikita-lutsenko-objc-swift-interoperability/ LET’S MIGRATE TO 3.0 REFERENCES David Bonnet - @iGranDav david.bonnet@cocoaheads.fr