SlideShare a Scribd company logo
1 of 61
Download to read offline
THINK SHARP, WRITE SWIFT
PASCAL BATTY
I’M A DEVELOPER
I’VE ALWAYS BEEN
A MAC NERD
I SAW A LOT OF
PEOPLE SWITCHING
I DON’T EVEN…
BASED ON SCIENTIFIC RESULTS
THE STAGES OF SWITCHING
😫 😯 😍
iOS
OS X
Apps
∞
Scripts + exe
OS X
Ubuntu
C# Swift
Object Oriented ✓ ✓
Type Inference ✓ ✓
Generics ✓ ✓
Tuples ✓ ✓
Lambdas ✓ ✓
Optional Chaining ✓ ✓
String Interpolation ✓ ✓
SWIFT VS C# FEATURE COMPARISON CHART
String Interpolation ✓ ✓
Operator overloading ✓ ✓
Null Coalescing ✓ ✓
Variadic Parameters ✓ ✓
Optional Parameters ✓ ✓
Extensions ✓ ✓
Auto-Properties ✓ ✓
Try/Catch ✓ ✓
Cool Logo ✓
THE GOOD OLD FIBONACCI SEQUENCE
LET’S COMPARE CODE
func fib(n: Int) -> Int
{
var fib0 = 0, fib1 = 1
for var i = 2; i <= n; i++
{
var tmp = fib0
fib0 = fib1
fib1 = tmp + fib1
}
return n > 0 ? fib1 : 0
}
static int fib(int n)
{
int fib0 = 0, fib1 = 1;
for (int i = 2; i <= n; i++)
{
int tmp = fib0;
fib0 = fib1;
fib1 = tmp + fib1;
}
return (n > 0 ? fib1 : 0);
}
C# Swift
as found on Wikibooks
SWIFT AND C#
ARE VERY SIMILAR
C# Swift
Garbage Collection Reference Counting
Interface Protocol
Constructor Initializer
const let
Linq MapReduce
Lambda Closure
func<> ->
SWIFT AND C# ARE KINDA SORTA SIMILAR
THE GOOD OLD FIBONACCI SEQUENCE
A FEW ADJUSTMENTS
func fib(n: Int) -> Int
{
var fib0 = 0, fib1 = 1
for var i = 2; i <= n; i++
{
var tmp = fib0
fib0 = fib1
fib1 = tmp + fib1
}
return n > 0 ? fib1 : 0
}
Variable was never mutated; consider changing to ‘let’ constant
THE GOOD OLD FIBONACCI SEQUENCE
A FEW ADJUSTMENTS
func fib(n: Int) -> Int
{
var fib0 = 0, fib1 = 1
for var i = 2; i <= n; i++
{
let tmp = fib0
fib0 = fib1
fib1 = tmp + fib1
}
return n > 0 ? fib1 : 0
}
++ is deprecated: it will be removed in Swift 3
THE GOOD OLD FIBONACCI SEQUENCE
A FEW ADJUSTMENTS
func fib(n: Int) -> Int
{
var fib0 = 0, fib1 = 1
for var i = 2; i <= n; i += 1
{
let tmp = fib0
fib0 = fib1
fib1 = tmp + fib1
}
return n > 0 ? fib1 : 0
}
C-Style for statement is deprecated and will be removed…
THE GOOD OLD FIBONACCI SEQUENCE
A FEW ADJUSTMENTS
func fib(n: Int) -> Int
{
var fib0 = 0, fib1 = 1
for i in 2...n
{
let tmp = fib0
fib0 = fib1
fib1 = tmp + fib1
}
return n > 0 ? fib1 : 0
}
Immutable value ‘i’ was never used; consider replacing with ‘_’
THE GOOD OLD FIBONACCI SEQUENCE
A FEW ADJUSTMENTS
func fib(n: Int) -> Int
{
var fib0 = 0, fib1 = 1
for _ in 2...n
{
let tmp = fib0
fib0 = fib1
fib1 = tmp + fib1
}
return n > 0 ? fib1 : 0
}
😌
THE COMPILER IS
PICKY BUT FRIENDLY
TYPE SYSTEM
LET US DIVE IN A LITTLE DEEPER
BUILDING BLOCKS
Class
Properties
Initializers
Instance Methods
Class Methods
Struct
Properties
Initializers
Instance methods
Static methods
Enum
Properties
Initializers
Instance methods
Static methods
VALUE TYPES
ARE AWESOME
I CAN’T ASK YOU TO JUST BELIEVE ME ON THIS
VALUE TYPES ARE AWESOME
▸ Immutability ensured by ‘let’
▸ No expensive boxing/unboxing
▸ Code is more thread-safe
▸ Performance is better
▸ Functional Programming is more convenient
LET US DIVE IN A LITTLE DEEPER
STANDARD TYPES
▸ Int, Float, Double
▸ Bool
▸ String, Character
▸ Array<T>, Dictionary<K: Hashable, V>, Set<T: Hashable>
THESE ARE ALL STRUCTS!
ENUMERABLES
YOU WON’T BELIEVE WHAT HAPPENS NEXT…
BRACE YOURSELVES…
ENUMERABLES AS YOU MAY KNOW THEM
enum Land {
case Forest
case Mountain
case Swamp
case Plains
case Island
}
enum Error : Int {
case NotFound = 404
case ServerError = 500
case Forbidden = 403
case Teapot = 418
}
Raw value can be
String, Character or
any numeric type
HERE COMES!
ENUMERABLES WITH ASSOCIATED VALUES!
enum PaymentMethod {
case Cash
case Check (Int)
case CreditCard (CardType, Int)
enum CardType { case Visa, MasterCard, Electron }
func display() {
switch self {
case Cash:
print("Paid by cash")
case let Check(number):
print("Paid by check #(number)")
case let CreditCard(type, number):
print("Paid by (type) #(number)")
}
}
}
let method = PaymentMethod.CreditCard(.Visa, 995423)
method.display()
NOT OVER YET!
… AND GENERICS!
enum Result<T, U> {
case Success(T)
case Error(U)
}
enum Optional<T> {
case Some(T)
case None
}
indirect enum Tree<T> {
case Empty
case Node(T, left: Tree<T>, right: Tree<T>)
}
OPTIONALS
(SPOILER: THEY’RE PRETTY COOL)
WHAT YOU MAY END UP DOING…
OPTIONALS IN THE WILD
let answer: String = "42"
let numericAnswer = Int(answer)
let byOneThousand = numericAnswer * 1000
let nineThousand: Float = 9 * 1000
let vegetaSays: String = "It's over (nineThousand) !!"
let nappaSays: String = "What!? " + String(nineThousand) + "?!"
VALUE OF OPTIONAL TYPE ‘INT?’ NOT UNWRAPPED;
DID YOU MEAN TO USE ‘!’ OR ‘?’ ?
Int?
BEAR WITH ME THERE
OPTIONALS
▸ Like nullables for all types!
▸ Variables, constants, arguments, properties or return
values
▸ You can’t use its value unless you unwrap it first
▸ If it is not Optional, it can never be nil
FORGOT TO CHECK NULLABILITY?
WON’T LET YOU USE THE VALUE
DO YOU KNOW THE ‘MAYBE’ MONAD ?
UNWRAPPING THE OPTIONAL
42
let answer: String = getAnswer()
let numericAnswer: Int? = Int(answer)
processNumericAnswer(numericAnswer)
???
Int?
Int nil
DO YOU KNOW THE ‘MAYBE’ MONAD ?
UNWRAPPING THE OPTIONAL
42
let answer: String = getAnswer()
let numericAnswer: Int? = Int(answer)
if let realAnswer: Int = numericAnswer {
processNumericAnswer(realAnswer)
}
else {
print("Please give a number")
} nil
Int?Int?
NOT EVERYTHING IS COMPULSORY
OPTIONAL PROPERTIES
struct Contact {
var firstName:String
var middleName:String?
var lastName:String
var emailAddress:String
var emailVerified:Bool
}
THAT’S A LOT OF PUNCTUATION!
NULL COALESCING AND OPTIONAL CHAINING
let answer: String = getAnswer()
let numericAnswer: Int? = Int(answer)
let sanitizedAnswer: Int = numericAnswer ?? 1
processNumericAnswer(sanitizedAnswer)
let contact: Contact? = getContact()
let email: String? = contact?.emailAddress
??
?.
FAMOUS LAST WORDS…
FORCE UNWRAP & IMPLICITLY UNWRAPPED OPTIONALS
!
« I KNOW WHAT I’M DOING.
IF YOU ENCOUNTER AN UNEXPECTED NIL
JUST CRASH AT RUNTIME »
THERE’S MORE!
PUT SOME LOGIC INSIDE YOUR TYPES!
FUN WITH PROPERTIES
struct Contact {
var firstName: String
var middleName: String?
var lastName: String
let securityNumber: Int
var fullName: String {
if let initial = middleName?.characters.first {
return "(firstName) (initial). (lastName)"
}
else {
return "(firstName) (lastName)"
}
}
var emailVerified: Bool
var emailAddress: String {
didSet {
emailVerified = false
}
}
}
MAP, FILTER, REDUCE, SORT
CLOSURES
let people:[Contact] = getContacts()
let targetNames:[String] = people
.filter({ contact in contact.lastName.hasPrefix("G") })
.map({ contact in contact.fullName })
.sort()
func multipleOf(factor: Int) -> Int -> Bool {
return { (number: Int) in number % factor == 0 }
}
let isEven = multipleOf(2)
isEven(4)
// Get the sum of multiples of 3 up to 100
(1...100)
.filter(multipleOf(3))
.reduce(0, combine: +)
https://github.com/mythz/swift-linq-examples
FUNCTIONAL
PROGRAMMING
IMAGINE THE POSSIBILITIES…
EXTENSIONS & PROTOCOLS
extension Contact {
func composeEmailBoilerplate() -> String { … }
var abbreviatedName: String { … }
}
protocol StringSerializable {
func serialize() -> String
}
extension StringSerializable {
func serialize() -> String { return "" }
}
extension Contact: StringSerializable {
func serialize() -> String { … }
}
PROTOCOL-ORIENTED
PROGRAMMING
WHERE TO START
YOU’VE GOT TO START SOMEWHERE
YOUR LEARNING ENVIRONMENT
OS X Ubuntu Windows
Xcode

Playground
REPL Ubuntu

Bash
WHEREVER YOU ARE
SWIFT SANDBOX
https://swiftlang.ng.bluemix.net
ONE OF THE PERKS OF DOING SWIFT ON THE MAC
PLAYGROUND
BECAUSE WE DON’T HAVE THE TIME TO SEE EVERYTHING
LEARN
▸ Updated eBook from Apple
▸ Available for free
▸ on iBooks
▸ on swift.org
▸ swiftdoc.org is a nice and fast
documentation website
SOLVE PROBLEMS!
Exercism.io Codingame.com
😫
Picky Compiler
SyntaxError Handling
Optionals
Incomplete

Generics
Argument

Naming
No

async/await
Value Types
for loops
A POLARIZING ASPECT
ARGUMENT NAMING
(1...100)
.filter(multipleOf(3))
.reduce(0, combine: +)
array.insert(0, 4)
array.insert(0, atIndex: 4)
😫
Picky Compiler
SyntaxError Handling
Optionals
Incomplete

Generics
Argument

Naming
No

async/await
Value Types
for loops
😯
Expressive code
guard.map().reduce()
Optionals
defer
Associated

Types
Protocols
typedef

Everything
enums
ClosuresValue Semantics
A CONVENTION-CREATING KEYWORD
GUARD
func multipleOf(factor: Int) -> Int -> Bool {
return { (number: Int) in number % factor == 0 }
}
A CONVENTION-CREATING KEYWORD
GUARD
func multipleOf(factor: Int) -> Int -> Bool {
guard factor != 0 else { return { _ in false } }
return { (number: Int) in number % factor == 0 }
}
😯
Expressive code
guard.map().reduce()
Optionals
defer
Associated

Types
Protocols
typedef

Everything
enums
ClosuresValue Semantics
😍
Object-Oriented

Programming
Functional

Programming
Protocol-Oriented

Programming
THINK SHARP,
WRITE SWIFT
THINK SWIFT
THANK YOU 💙
Pascal Batty
@scalbatty
scalbatty
blog.soat.fr https://github.com/scalbatty/Think-Sharp-Write-Swift

More Related Content

What's hot

String Handling in c++
String Handling in c++String Handling in c++
String Handling in c++
Fahim Adil
 
lpSolve - R Library
lpSolve - R LibrarylpSolve - R Library
lpSolve - R Library
David Faris
 
100 c interview questions answers
100 c interview questions answers100 c interview questions answers
100 c interview questions answers
Sareen Kumar
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2
Warui Maina
 

What's hot (20)

Strings
StringsStrings
Strings
 
3 kotlin vs. java- what kotlin has that java does not
3  kotlin vs. java- what kotlin has that java does not3  kotlin vs. java- what kotlin has that java does not
3 kotlin vs. java- what kotlin has that java does not
 
String Handling in c++
String Handling in c++String Handling in c++
String Handling in c++
 
Reading Keyboard Output
Reading Keyboard OutputReading Keyboard Output
Reading Keyboard Output
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
 
Erlang bootstrap course
Erlang bootstrap courseErlang bootstrap course
Erlang bootstrap course
 
9 character string &amp; string library
9  character string &amp; string library9  character string &amp; string library
9 character string &amp; string library
 
Loops_in_Rv1.2b
Loops_in_Rv1.2bLoops_in_Rv1.2b
Loops_in_Rv1.2b
 
Ad hoc Polymorphism using Type Classes and Cats
Ad hoc Polymorphism using Type Classes and CatsAd hoc Polymorphism using Type Classes and Cats
Ad hoc Polymorphism using Type Classes and Cats
 
Lecture 6
Lecture 6Lecture 6
Lecture 6
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
 
4 operators, expressions &amp; statements
4  operators, expressions &amp; statements4  operators, expressions &amp; statements
4 operators, expressions &amp; statements
 
Rust Intro
Rust IntroRust Intro
Rust Intro
 
Keygenning using the Z3 SMT Solver
Keygenning using the Z3 SMT SolverKeygenning using the Z3 SMT Solver
Keygenning using the Z3 SMT Solver
 
lpSolve - R Library
lpSolve - R LibrarylpSolve - R Library
lpSolve - R Library
 
Learn python in 20 minutes
Learn python in 20 minutesLearn python in 20 minutes
Learn python in 20 minutes
 
100 c interview questions answers
100 c interview questions answers100 c interview questions answers
100 c interview questions answers
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2
 
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
 
Lecture 17 - Strings
Lecture 17 - StringsLecture 17 - Strings
Lecture 17 - Strings
 

Viewers also liked (10)

Homework One Content Analysis
Homework One  Content AnalysisHomework One  Content Analysis
Homework One Content Analysis
 
Неделя равноправия
Неделя равноправияНеделя равноправия
Неделя равноправия
 
Photography Planning
Photography PlanningPhotography Planning
Photography Planning
 
Cute cat videos on youtube
Cute cat videos on youtubeCute cat videos on youtube
Cute cat videos on youtube
 
Boosting Culture Email Version
Boosting Culture Email VersionBoosting Culture Email Version
Boosting Culture Email Version
 
Content
Content Content
Content
 
Respect Relationships Reconciliation
Respect Relationships ReconciliationRespect Relationships Reconciliation
Respect Relationships Reconciliation
 
Верим в полное возрождение стрит ритейла к 2017году
Верим в полное возрождение стрит ритейла к 2017годуВерим в полное возрождение стрит ритейла к 2017году
Верим в полное возрождение стрит ритейла к 2017году
 
Sasaki Associates Guangyang Island Park
Sasaki Associates Guangyang Island ParkSasaki Associates Guangyang Island Park
Sasaki Associates Guangyang Island Park
 
Fuuny cat videos
Fuuny cat videosFuuny cat videos
Fuuny cat videos
 

Similar to Think sharp, write swift

Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
Abed Bukhari
 
Haskell retrospective
Haskell retrospectiveHaskell retrospective
Haskell retrospective
chenge2k
 

Similar to Think sharp, write swift (20)

Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Kotlin as a Better Java
Kotlin as a Better JavaKotlin as a Better Java
Kotlin as a Better Java
 
Basics of Javascript
Basics of JavascriptBasics of Javascript
Basics of Javascript
 
Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
 
FYP Final Presentation
FYP Final PresentationFYP Final Presentation
FYP Final Presentation
 
Fp
FpFp
Fp
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
 
Perl 6 in Context
Perl 6 in ContextPerl 6 in Context
Perl 6 in Context
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme Swift
 
Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)
 
Intro toswift1
Intro toswift1Intro toswift1
Intro toswift1
 
Class 4: For and while
Class 4: For and whileClass 4: For and while
Class 4: For and while
 
Haskell retrospective
Haskell retrospectiveHaskell retrospective
Haskell retrospective
 
Making JavaScript Libraries More Approachable
Making JavaScript Libraries More ApproachableMaking JavaScript Libraries More Approachable
Making JavaScript Libraries More Approachable
 
Introduction to Kotlin.pptx
Introduction to Kotlin.pptxIntroduction to Kotlin.pptx
Introduction to Kotlin.pptx
 
01 Introduction to Kotlin - Programming in Kotlin.pptx
01 Introduction to Kotlin - Programming in Kotlin.pptx01 Introduction to Kotlin - Programming in Kotlin.pptx
01 Introduction to Kotlin - Programming in Kotlin.pptx
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
 
Ur Domain Haz Monoids DDDx NYC 2014
Ur Domain Haz Monoids DDDx NYC 2014Ur Domain Haz Monoids DDDx NYC 2014
Ur Domain Haz Monoids DDDx NYC 2014
 
A Few Interesting Things in Apple's Swift Programming Language
A Few Interesting Things in Apple's Swift Programming LanguageA Few Interesting Things in Apple's Swift Programming Language
A Few Interesting Things in Apple's Swift Programming Language
 

Recently uploaded

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Recently uploaded (20)

Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 

Think sharp, write swift

  • 1. THINK SHARP, WRITE SWIFT PASCAL BATTY
  • 4.
  • 5.
  • 6. I SAW A LOT OF PEOPLE SWITCHING
  • 8. BASED ON SCIENTIFIC RESULTS THE STAGES OF SWITCHING 😫 😯 😍
  • 9. iOS OS X Apps ∞ Scripts + exe OS X Ubuntu
  • 10. C# Swift Object Oriented ✓ ✓ Type Inference ✓ ✓ Generics ✓ ✓ Tuples ✓ ✓ Lambdas ✓ ✓ Optional Chaining ✓ ✓ String Interpolation ✓ ✓ SWIFT VS C# FEATURE COMPARISON CHART
  • 11. String Interpolation ✓ ✓ Operator overloading ✓ ✓ Null Coalescing ✓ ✓ Variadic Parameters ✓ ✓ Optional Parameters ✓ ✓ Extensions ✓ ✓ Auto-Properties ✓ ✓ Try/Catch ✓ ✓ Cool Logo ✓
  • 12. THE GOOD OLD FIBONACCI SEQUENCE LET’S COMPARE CODE func fib(n: Int) -> Int { var fib0 = 0, fib1 = 1 for var i = 2; i <= n; i++ { var tmp = fib0 fib0 = fib1 fib1 = tmp + fib1 } return n > 0 ? fib1 : 0 } static int fib(int n) { int fib0 = 0, fib1 = 1; for (int i = 2; i <= n; i++) { int tmp = fib0; fib0 = fib1; fib1 = tmp + fib1; } return (n > 0 ? fib1 : 0); } C# Swift as found on Wikibooks
  • 13. SWIFT AND C# ARE VERY SIMILAR
  • 14. C# Swift Garbage Collection Reference Counting Interface Protocol Constructor Initializer const let Linq MapReduce Lambda Closure func<> -> SWIFT AND C# ARE KINDA SORTA SIMILAR
  • 15. THE GOOD OLD FIBONACCI SEQUENCE A FEW ADJUSTMENTS func fib(n: Int) -> Int { var fib0 = 0, fib1 = 1 for var i = 2; i <= n; i++ { var tmp = fib0 fib0 = fib1 fib1 = tmp + fib1 } return n > 0 ? fib1 : 0 } Variable was never mutated; consider changing to ‘let’ constant
  • 16. THE GOOD OLD FIBONACCI SEQUENCE A FEW ADJUSTMENTS func fib(n: Int) -> Int { var fib0 = 0, fib1 = 1 for var i = 2; i <= n; i++ { let tmp = fib0 fib0 = fib1 fib1 = tmp + fib1 } return n > 0 ? fib1 : 0 } ++ is deprecated: it will be removed in Swift 3
  • 17. THE GOOD OLD FIBONACCI SEQUENCE A FEW ADJUSTMENTS func fib(n: Int) -> Int { var fib0 = 0, fib1 = 1 for var i = 2; i <= n; i += 1 { let tmp = fib0 fib0 = fib1 fib1 = tmp + fib1 } return n > 0 ? fib1 : 0 } C-Style for statement is deprecated and will be removed…
  • 18. THE GOOD OLD FIBONACCI SEQUENCE A FEW ADJUSTMENTS func fib(n: Int) -> Int { var fib0 = 0, fib1 = 1 for i in 2...n { let tmp = fib0 fib0 = fib1 fib1 = tmp + fib1 } return n > 0 ? fib1 : 0 } Immutable value ‘i’ was never used; consider replacing with ‘_’
  • 19. THE GOOD OLD FIBONACCI SEQUENCE A FEW ADJUSTMENTS func fib(n: Int) -> Int { var fib0 = 0, fib1 = 1 for _ in 2...n { let tmp = fib0 fib0 = fib1 fib1 = tmp + fib1 } return n > 0 ? fib1 : 0 } 😌
  • 20. THE COMPILER IS PICKY BUT FRIENDLY
  • 22. LET US DIVE IN A LITTLE DEEPER BUILDING BLOCKS Class Properties Initializers Instance Methods Class Methods Struct Properties Initializers Instance methods Static methods Enum Properties Initializers Instance methods Static methods
  • 24. I CAN’T ASK YOU TO JUST BELIEVE ME ON THIS VALUE TYPES ARE AWESOME ▸ Immutability ensured by ‘let’ ▸ No expensive boxing/unboxing ▸ Code is more thread-safe ▸ Performance is better ▸ Functional Programming is more convenient
  • 25. LET US DIVE IN A LITTLE DEEPER STANDARD TYPES ▸ Int, Float, Double ▸ Bool ▸ String, Character ▸ Array<T>, Dictionary<K: Hashable, V>, Set<T: Hashable> THESE ARE ALL STRUCTS!
  • 26. ENUMERABLES YOU WON’T BELIEVE WHAT HAPPENS NEXT…
  • 27. BRACE YOURSELVES… ENUMERABLES AS YOU MAY KNOW THEM enum Land { case Forest case Mountain case Swamp case Plains case Island } enum Error : Int { case NotFound = 404 case ServerError = 500 case Forbidden = 403 case Teapot = 418 } Raw value can be String, Character or any numeric type
  • 28. HERE COMES! ENUMERABLES WITH ASSOCIATED VALUES! enum PaymentMethod { case Cash case Check (Int) case CreditCard (CardType, Int) enum CardType { case Visa, MasterCard, Electron } func display() { switch self { case Cash: print("Paid by cash") case let Check(number): print("Paid by check #(number)") case let CreditCard(type, number): print("Paid by (type) #(number)") } } } let method = PaymentMethod.CreditCard(.Visa, 995423) method.display()
  • 29. NOT OVER YET! … AND GENERICS! enum Result<T, U> { case Success(T) case Error(U) } enum Optional<T> { case Some(T) case None } indirect enum Tree<T> { case Empty case Node(T, left: Tree<T>, right: Tree<T>) }
  • 31. WHAT YOU MAY END UP DOING… OPTIONALS IN THE WILD let answer: String = "42" let numericAnswer = Int(answer) let byOneThousand = numericAnswer * 1000 let nineThousand: Float = 9 * 1000 let vegetaSays: String = "It's over (nineThousand) !!" let nappaSays: String = "What!? " + String(nineThousand) + "?!" VALUE OF OPTIONAL TYPE ‘INT?’ NOT UNWRAPPED; DID YOU MEAN TO USE ‘!’ OR ‘?’ ? Int?
  • 32. BEAR WITH ME THERE OPTIONALS ▸ Like nullables for all types! ▸ Variables, constants, arguments, properties or return values ▸ You can’t use its value unless you unwrap it first ▸ If it is not Optional, it can never be nil
  • 33. FORGOT TO CHECK NULLABILITY? WON’T LET YOU USE THE VALUE
  • 34. DO YOU KNOW THE ‘MAYBE’ MONAD ? UNWRAPPING THE OPTIONAL 42 let answer: String = getAnswer() let numericAnswer: Int? = Int(answer) processNumericAnswer(numericAnswer) ??? Int? Int nil
  • 35. DO YOU KNOW THE ‘MAYBE’ MONAD ? UNWRAPPING THE OPTIONAL 42 let answer: String = getAnswer() let numericAnswer: Int? = Int(answer) if let realAnswer: Int = numericAnswer { processNumericAnswer(realAnswer) } else { print("Please give a number") } nil Int?Int?
  • 36. NOT EVERYTHING IS COMPULSORY OPTIONAL PROPERTIES struct Contact { var firstName:String var middleName:String? var lastName:String var emailAddress:String var emailVerified:Bool }
  • 37. THAT’S A LOT OF PUNCTUATION! NULL COALESCING AND OPTIONAL CHAINING let answer: String = getAnswer() let numericAnswer: Int? = Int(answer) let sanitizedAnswer: Int = numericAnswer ?? 1 processNumericAnswer(sanitizedAnswer) let contact: Contact? = getContact() let email: String? = contact?.emailAddress ?? ?.
  • 38. FAMOUS LAST WORDS… FORCE UNWRAP & IMPLICITLY UNWRAPPED OPTIONALS ! « I KNOW WHAT I’M DOING. IF YOU ENCOUNTER AN UNEXPECTED NIL JUST CRASH AT RUNTIME »
  • 40. PUT SOME LOGIC INSIDE YOUR TYPES! FUN WITH PROPERTIES struct Contact { var firstName: String var middleName: String? var lastName: String let securityNumber: Int var fullName: String { if let initial = middleName?.characters.first { return "(firstName) (initial). (lastName)" } else { return "(firstName) (lastName)" } } var emailVerified: Bool var emailAddress: String { didSet { emailVerified = false } } }
  • 41. MAP, FILTER, REDUCE, SORT CLOSURES let people:[Contact] = getContacts() let targetNames:[String] = people .filter({ contact in contact.lastName.hasPrefix("G") }) .map({ contact in contact.fullName }) .sort() func multipleOf(factor: Int) -> Int -> Bool { return { (number: Int) in number % factor == 0 } } let isEven = multipleOf(2) isEven(4) // Get the sum of multiples of 3 up to 100 (1...100) .filter(multipleOf(3)) .reduce(0, combine: +) https://github.com/mythz/swift-linq-examples
  • 43. IMAGINE THE POSSIBILITIES… EXTENSIONS & PROTOCOLS extension Contact { func composeEmailBoilerplate() -> String { … } var abbreviatedName: String { … } } protocol StringSerializable { func serialize() -> String } extension StringSerializable { func serialize() -> String { return "" } } extension Contact: StringSerializable { func serialize() -> String { … } }
  • 46. YOU’VE GOT TO START SOMEWHERE YOUR LEARNING ENVIRONMENT OS X Ubuntu Windows Xcode
 Playground REPL Ubuntu
 Bash
  • 47. WHEREVER YOU ARE SWIFT SANDBOX https://swiftlang.ng.bluemix.net
  • 48. ONE OF THE PERKS OF DOING SWIFT ON THE MAC PLAYGROUND
  • 49. BECAUSE WE DON’T HAVE THE TIME TO SEE EVERYTHING LEARN ▸ Updated eBook from Apple ▸ Available for free ▸ on iBooks ▸ on swift.org ▸ swiftdoc.org is a nice and fast documentation website
  • 52. A POLARIZING ASPECT ARGUMENT NAMING (1...100) .filter(multipleOf(3)) .reduce(0, combine: +) array.insert(0, 4) array.insert(0, atIndex: 4)
  • 55. A CONVENTION-CREATING KEYWORD GUARD func multipleOf(factor: Int) -> Int -> Bool { return { (number: Int) in number % factor == 0 } }
  • 56. A CONVENTION-CREATING KEYWORD GUARD func multipleOf(factor: Int) -> Int -> Bool { guard factor != 0 else { return { _ in false } } return { (number: Int) in number % factor == 0 } }
  • 61. THANK YOU 💙 Pascal Batty @scalbatty scalbatty blog.soat.fr https://github.com/scalbatty/Think-Sharp-Write-Swift