SlideShare une entreprise Scribd logo
1  sur  20
A Few Interesting
Things In Swift
Ara Hacopian
B’more on Rails
6/10/2014
Ara Hacopian
http://www.smartlogic.io
http://www.twitter.com/ahacop
http://www.github.com/ahacop
SmartLogic
Some Cool Stuff
● Type Inference
● Explicit Mutability
● Optionals
● Named Parameters
● Enumerations
● Exhaustive Switch
● Closures
● Generics
Type Inference
You can do this:
var x : Int = 0
var y : String = “foobar”
var z : Bool = true
Or, you can just do this:
var x = 0
var y = “foobar”
var z = true
Type Inference
var x = 1
x = “quux” ← COMPILER ERROR
Typed Collections
var mammals: String[] = [“dog”, “cat”]
var people = [“dan”, “eric”, “tom”]
var numbers = [1, 2, 3]
numbers.append(“ara”) ←COMPILER ERROR
Explicit Mutability
var x = 0
x = 1
x // x == 1
let y = 0
y = 1 ← COMPILER ERROR
Never Be Nil
var x : Int = 0
x = nil ← COMPILER ERROR
Optionals
Optionals handle the absence of a value.
Either:
1. there is some value, and it equals x
var foo : Int? = 41 // { Some 41 }
1. or, there is no value at all
var bar : Int? // nil
Optional Declaration
var intOptional : Int?
var stringOptional : String?
var boolOptional : Bool?
Optionals: Unwrapping
You can unwrap the value contained in the
optional by using the bang operator, like so:
var foo : Int? = 41
foo! == 41 // true
But if it’s nil, you will get a runtime error,
so don’t do that.
Optional Binding
var possibleNumber = "2"
if let actualNumber =
possibleNumber.toInt() {
println("(possibleNumber) has an integer
value of (actualNumber)")
} else {
println("(possibleNumber) could not be
converted to an integer")
}
Optional Chaining
class Person {
var name : String
var address : Address?
init(name:String, atAddress address:Address?=nil) {
self.name = name
self.address = address
}
}
class Address {
func sendLetter() {
println("Sent a letter!")
}
}
let ara = Person(name: "Ara")
let paul = Person(name: "Paul", atAddress:Address())
let people = [ara, paul]
for person in people {
person.address?.sendLetter()
}
External Param Names
func join(
string s1: String,
toString s2: String,
withJoiner joiner: String) -> String {
return s1 + joiner + s2
}
join(string: "hello", toString: "world",
withJoiner: ", ")
Enumerations
enum Compass {
case North, South, West, East
}
enum Status {
case OnTime, Delayed(Int, String)
}
Exhaustive Switch
In Swift, the compiler enforces that a switch statement contains a case
for every possible value for that type.
enum Status {
case OnTime, Delayed(Int, String)
}
let trainStatus = Status.Delayed(5, “banana on tracks”)
switch trainStatus {
case .OnTime:
println(“Train is on time!”)
case .Delayed(let minutes, let reason):
println(“Train delay: (minutes) minute(s), Reason: (reason)”)
Closures
Just like blocks in ObjC...but there’s a lot of optional syntax.
let names = ["Paul", "Ara", "Eric", "Tom", "Dan"]
func backwards(s1: String, s2: String) -> Bool {
return s1 > s2
}
1. sort(names, backwards)
2. sort(names, { (s1: String, s2: String) -> Bool in return s1 > s2
})
3. sort(names, { s1, s2 in return s1 > s2 } )
4. sort(names, { s1, s2 in s1 > s2 } )
5. sort(names, { $0 > $1 } )
6. sort(names, >)
Generics
struct IntStack {
var items = Int[]()
mutating func push(item: Int) {
items.append(item)
}
mutating func pop() -> Int {
return items.removeLast()
}
}
Generics
struct Stack<T> {
var items = T[]()
mutating func push(item: T) {
items.append(item)
}
mutating func pop() -> T {
return items.removeLast()
}
}
Questions?
http://www.smartlogic.io/
http://www.twitter.com/ahacop
http://www.github.com/ahacop

Contenu connexe

Tendances

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
Giordano Scalzo
 

Tendances (20)

Swiftの関数型っぽい部分
Swiftの関数型っぽい部分Swiftの関数型っぽい部分
Swiftの関数型っぽい部分
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
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
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
 
Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015
 
ProgrammingwithGOLang
ProgrammingwithGOLangProgrammingwithGOLang
ProgrammingwithGOLang
 
Don't do this
Don't do thisDon't do this
Don't do this
 
Javascript ES6 generators
Javascript ES6 generatorsJavascript ES6 generators
Javascript ES6 generators
 
Stupid Awesome Python Tricks
Stupid Awesome Python TricksStupid Awesome Python Tricks
Stupid Awesome Python Tricks
 
Functional Pe(a)rls - the Purely Functional Datastructures edition
Functional Pe(a)rls - the Purely Functional Datastructures editionFunctional Pe(a)rls - the Purely Functional Datastructures edition
Functional Pe(a)rls - the Purely Functional Datastructures edition
 
Is Haskell an acceptable Perl?
Is Haskell an acceptable Perl?Is Haskell an acceptable Perl?
Is Haskell an acceptable Perl?
 
... now write an interpreter (PHPem 2016)
... now write an interpreter (PHPem 2016)... now write an interpreter (PHPem 2016)
... now write an interpreter (PHPem 2016)
 
Fun never stops. introduction to haskell programming language
Fun never stops. introduction to haskell programming languageFun never stops. introduction to haskell programming language
Fun never stops. introduction to haskell programming language
 
Invertible-syntax 入門
Invertible-syntax 入門Invertible-syntax 入門
Invertible-syntax 入門
 
Hello Swift 3/5 - Function
Hello Swift 3/5 - FunctionHello Swift 3/5 - Function
Hello Swift 3/5 - Function
 
Swift internals
Swift internalsSwift internals
Swift internals
 

En vedette

Sparq lreference 1.8-us
Sparq lreference 1.8-usSparq lreference 1.8-us
Sparq lreference 1.8-us
Ajay Ohri
 
Performance data visualization with r and tableau
Performance data visualization with r and tableauPerformance data visualization with r and tableau
Performance data visualization with r and tableau
Enkitec
 

En vedette (20)

Sparq lreference 1.8-us
Sparq lreference 1.8-usSparq lreference 1.8-us
Sparq lreference 1.8-us
 
Data Visualization in R
Data Visualization in RData Visualization in R
Data Visualization in R
 
R programming Language , Rahul Singh
R programming Language , Rahul SinghR programming Language , Rahul Singh
R programming Language , Rahul Singh
 
Performance data visualization with r and tableau
Performance data visualization with r and tableauPerformance data visualization with r and tableau
Performance data visualization with r and tableau
 
Welcome to Swift (CocoaCoder 6/12/14)
Welcome to Swift (CocoaCoder 6/12/14)Welcome to Swift (CocoaCoder 6/12/14)
Welcome to Swift (CocoaCoder 6/12/14)
 
How to make workout app for watch os 2
How to make workout app for watch os 2How to make workout app for watch os 2
How to make workout app for watch os 2
 
Adapt or Die DevJam: San Francisco, Sept 27 2016
Adapt or Die DevJam: San Francisco, Sept 27 2016Adapt or Die DevJam: San Francisco, Sept 27 2016
Adapt or Die DevJam: San Francisco, Sept 27 2016
 
Mindbody: A Digital Transformation Story
Mindbody: A Digital Transformation StoryMindbody: A Digital Transformation Story
Mindbody: A Digital Transformation Story
 
London Adapt or Die: Opening Keynote with Chet Kapoor
London Adapt or Die: Opening Keynote with Chet KapoorLondon Adapt or Die: Opening Keynote with Chet Kapoor
London Adapt or Die: Opening Keynote with Chet Kapoor
 
From IoT to biohacking. Trends that were, are and will be popular.
From IoT to biohacking. Trends that were, are and will be popular. From IoT to biohacking. Trends that were, are and will be popular.
From IoT to biohacking. Trends that were, are and will be popular.
 
London adapt or-die opening keynote chet kapoor
London adapt or-die opening keynote chet kapoorLondon adapt or-die opening keynote chet kapoor
London adapt or-die opening keynote chet kapoor
 
Class ppt intro to r
Class ppt intro to rClass ppt intro to r
Class ppt intro to r
 
London Adapt or Die: Lunch keynote
London Adapt or Die: Lunch keynoteLondon Adapt or Die: Lunch keynote
London Adapt or Die: Lunch keynote
 
Linux PV on HVM
Linux PV on HVMLinux PV on HVM
Linux PV on HVM
 
Becoming the Uncarrier: T-Mobile's Digital Journey
Becoming the Uncarrier: T-Mobile's Digital JourneyBecoming the Uncarrier: T-Mobile's Digital Journey
Becoming the Uncarrier: T-Mobile's Digital Journey
 
API Governance in the Enterprise
API Governance in the EnterpriseAPI Governance in the Enterprise
API Governance in the Enterprise
 
London Adapt or Die: Five Things Enterprises Should Know About Serverless
London Adapt or Die: Five Things Enterprises Should Know About ServerlessLondon Adapt or Die: Five Things Enterprises Should Know About Serverless
London Adapt or Die: Five Things Enterprises Should Know About Serverless
 
API Management and Kubernetes
API Management and KubernetesAPI Management and Kubernetes
API Management and Kubernetes
 
London Adapt or Die: Securing your APIs the Right Way!
London Adapt or Die: Securing your APIs the Right Way!London Adapt or Die: Securing your APIs the Right Way!
London Adapt or Die: Securing your APIs the Right Way!
 
Adapt or Die: Keynote with Anant Jhingran
Adapt or Die: Keynote with Anant JhingranAdapt or Die: Keynote with Anant Jhingran
Adapt or Die: Keynote with Anant Jhingran
 

Similaire à A Few Interesting Things in Apple's Swift Programming Language

Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
Loïc Descotte
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
Sway Wang
 

Similaire à A Few Interesting Things in Apple's Swift Programming Language (20)

An Introduction to Scala (2014)
An Introduction to Scala (2014)An Introduction to Scala (2014)
An Introduction to Scala (2014)
 
Naïveté vs. Experience
Naïveté vs. ExperienceNaïveté vs. Experience
Naïveté vs. Experience
 
Swift Study #7
Swift Study #7Swift Study #7
Swift Study #7
 
Go Java, Go!
Go Java, Go!Go Java, Go!
Go Java, Go!
 
Think sharp, write swift
Think sharp, write swiftThink sharp, write swift
Think sharp, write swift
 
Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2
 
JavaScript @ CTK
JavaScript @ CTKJavaScript @ CTK
JavaScript @ CTK
 
Benefits of Kotlin
Benefits of KotlinBenefits of Kotlin
Benefits of Kotlin
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Intro toswift1
Intro toswift1Intro toswift1
Intro toswift1
 
NUS iOS Swift Talk
NUS iOS Swift TalkNUS iOS Swift Talk
NUS iOS Swift Talk
 
Scala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldScala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereld
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlin
 
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlin
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Introduction to TypeScript
Introduction to TypeScriptIntroduction to TypeScript
Introduction to TypeScript
 
Exploring Koltin on Android
Exploring Koltin on AndroidExploring Koltin on Android
Exploring Koltin on Android
 

Plus de SmartLogic

How SmartLogic Uses Chef-Dan Ivovich
How SmartLogic Uses Chef-Dan IvovichHow SmartLogic Uses Chef-Dan Ivovich
How SmartLogic Uses Chef-Dan Ivovich
SmartLogic
 

Plus de SmartLogic (20)

Writing Game Servers with Elixir
Writing Game Servers with ElixirWriting Game Servers with Elixir
Writing Game Servers with Elixir
 
All Aboard The Stateful Train
All Aboard The Stateful TrainAll Aboard The Stateful Train
All Aboard The Stateful Train
 
DC |> Elixir Meetup - Going off the Rails into Elixir - Dan Ivovich
DC |> Elixir Meetup - Going off the Rails into Elixir - Dan IvovichDC |> Elixir Meetup - Going off the Rails into Elixir - Dan Ivovich
DC |> Elixir Meetup - Going off the Rails into Elixir - Dan Ivovich
 
Monitoring Your Elixir Application with Prometheus
Monitoring Your Elixir Application with PrometheusMonitoring Your Elixir Application with Prometheus
Monitoring Your Elixir Application with Prometheus
 
Going Multi-Node
Going Multi-NodeGoing Multi-Node
Going Multi-Node
 
Kubernetes and docker
Kubernetes and dockerKubernetes and docker
Kubernetes and docker
 
Serializing Value Objects-Ara Hacopian
Serializing Value Objects-Ara HacopianSerializing Value Objects-Ara Hacopian
Serializing Value Objects-Ara Hacopian
 
Guide to food foraging by SmartLogic's Kei Ellerbrock
Guide to food foraging by SmartLogic's Kei EllerbrockGuide to food foraging by SmartLogic's Kei Ellerbrock
Guide to food foraging by SmartLogic's Kei Ellerbrock
 
Introduction to Type Script by Sam Goldman, SmartLogic
Introduction to Type Script by Sam Goldman, SmartLogicIntroduction to Type Script by Sam Goldman, SmartLogic
Introduction to Type Script by Sam Goldman, SmartLogic
 
How SmartLogic Uses Chef-Dan Ivovich
How SmartLogic Uses Chef-Dan IvovichHow SmartLogic Uses Chef-Dan Ivovich
How SmartLogic Uses Chef-Dan Ivovich
 
Effective ActiveRecord
Effective ActiveRecordEffective ActiveRecord
Effective ActiveRecord
 
An Introduction to Reactive Cocoa
An Introduction to Reactive CocoaAn Introduction to Reactive Cocoa
An Introduction to Reactive Cocoa
 
iOS Development Methodology
iOS Development MethodologyiOS Development Methodology
iOS Development Methodology
 
CSS Preprocessors to the Rescue!
CSS Preprocessors to the Rescue!CSS Preprocessors to the Rescue!
CSS Preprocessors to the Rescue!
 
Deploying Rails Apps with Chef and Capistrano
 Deploying Rails Apps with Chef and Capistrano Deploying Rails Apps with Chef and Capistrano
Deploying Rails Apps with Chef and Capistrano
 
From Slacker to Hacker, Practical Tips for Learning to Code
From Slacker to Hacker, Practical Tips for Learning to CodeFrom Slacker to Hacker, Practical Tips for Learning to Code
From Slacker to Hacker, Practical Tips for Learning to Code
 
The Language of Abstraction in Software Development
The Language of Abstraction in Software DevelopmentThe Language of Abstraction in Software Development
The Language of Abstraction in Software Development
 
Android Testing: An Overview
Android Testing: An OverviewAndroid Testing: An Overview
Android Testing: An Overview
 
Intro to DTCoreText: Moving Past UIWebView | iOS Development
Intro to DTCoreText: Moving Past UIWebView | iOS DevelopmentIntro to DTCoreText: Moving Past UIWebView | iOS Development
Intro to DTCoreText: Moving Past UIWebView | iOS Development
 
Logstash: Get to know your logs
Logstash: Get to know your logsLogstash: Get to know your logs
Logstash: Get to know your logs
 

Dernier

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

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
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
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
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
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...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
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
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
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...
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 

A Few Interesting Things in Apple's Swift Programming Language

  • 1. A Few Interesting Things In Swift Ara Hacopian B’more on Rails 6/10/2014
  • 3. Some Cool Stuff ● Type Inference ● Explicit Mutability ● Optionals ● Named Parameters ● Enumerations ● Exhaustive Switch ● Closures ● Generics
  • 4. Type Inference You can do this: var x : Int = 0 var y : String = “foobar” var z : Bool = true Or, you can just do this: var x = 0 var y = “foobar” var z = true
  • 5. Type Inference var x = 1 x = “quux” ← COMPILER ERROR
  • 6. Typed Collections var mammals: String[] = [“dog”, “cat”] var people = [“dan”, “eric”, “tom”] var numbers = [1, 2, 3] numbers.append(“ara”) ←COMPILER ERROR
  • 7. Explicit Mutability var x = 0 x = 1 x // x == 1 let y = 0 y = 1 ← COMPILER ERROR
  • 8. Never Be Nil var x : Int = 0 x = nil ← COMPILER ERROR
  • 9. Optionals Optionals handle the absence of a value. Either: 1. there is some value, and it equals x var foo : Int? = 41 // { Some 41 } 1. or, there is no value at all var bar : Int? // nil
  • 10. Optional Declaration var intOptional : Int? var stringOptional : String? var boolOptional : Bool?
  • 11. Optionals: Unwrapping You can unwrap the value contained in the optional by using the bang operator, like so: var foo : Int? = 41 foo! == 41 // true But if it’s nil, you will get a runtime error, so don’t do that.
  • 12. Optional Binding var possibleNumber = "2" if let actualNumber = possibleNumber.toInt() { println("(possibleNumber) has an integer value of (actualNumber)") } else { println("(possibleNumber) could not be converted to an integer") }
  • 13. Optional Chaining class Person { var name : String var address : Address? init(name:String, atAddress address:Address?=nil) { self.name = name self.address = address } } class Address { func sendLetter() { println("Sent a letter!") } } let ara = Person(name: "Ara") let paul = Person(name: "Paul", atAddress:Address()) let people = [ara, paul] for person in people { person.address?.sendLetter() }
  • 14. External Param Names func join( string s1: String, toString s2: String, withJoiner joiner: String) -> String { return s1 + joiner + s2 } join(string: "hello", toString: "world", withJoiner: ", ")
  • 15. Enumerations enum Compass { case North, South, West, East } enum Status { case OnTime, Delayed(Int, String) }
  • 16. Exhaustive Switch In Swift, the compiler enforces that a switch statement contains a case for every possible value for that type. enum Status { case OnTime, Delayed(Int, String) } let trainStatus = Status.Delayed(5, “banana on tracks”) switch trainStatus { case .OnTime: println(“Train is on time!”) case .Delayed(let minutes, let reason): println(“Train delay: (minutes) minute(s), Reason: (reason)”)
  • 17. Closures Just like blocks in ObjC...but there’s a lot of optional syntax. let names = ["Paul", "Ara", "Eric", "Tom", "Dan"] func backwards(s1: String, s2: String) -> Bool { return s1 > s2 } 1. sort(names, backwards) 2. sort(names, { (s1: String, s2: String) -> Bool in return s1 > s2 }) 3. sort(names, { s1, s2 in return s1 > s2 } ) 4. sort(names, { s1, s2 in s1 > s2 } ) 5. sort(names, { $0 > $1 } ) 6. sort(names, >)
  • 18. Generics struct IntStack { var items = Int[]() mutating func push(item: Int) { items.append(item) } mutating func pop() -> Int { return items.removeLast() } }
  • 19. Generics struct Stack<T> { var items = T[]() mutating func push(item: T) { items.append(item) } mutating func pop() -> T { return items.removeLast() } }

Notes de l'éditeur

  1. “Swift is a type safe language. A type safe language encourages you to be clear about the types of values your code can work with. If part of your code expects a String, you can’t pass it an Int by mistake. Because Swift is type safe, it performs type checks when compiling your code and flags any mismatched types as errors. This enables you to catch and fix errors as early as possible in the development process.” But it also has a feature called Type Inference which means if the compiler can infer the type of a variable from the context of its declaration, you don’t need to explicitly write the type, it will be inferred.
  2. Type inference means, that you even if you don’t provide a type annotation, but the var is still strongly typed -- so you can’t clobber it with a different type.
  3. Swift provides two collection types: arrays and dictionaries, for storing collections of values. Collections are strongly typed, so you can’t insert the wrong value into a collection, and you always know what you’re going to get when you retrieve a value. As with other types, the type can be inferred
  4. For collections: an array = can’t change the size, but can’t replace a value at an index dictionary = can’t change values
  5. Values of most types can never be nil. Every value must be initialized before it is used. So how do you deal with the possibility of the absence of a value?
  6. Optionals say either “there is a value, and it equals x” or “there isn’t a value at all”. Optionals are similar to using nil with pointers in Objective-C, but they work for any type, not just classes.” “Optionals are an example of the fact that Swift is a type safe language. Swift helps you to be clear about the types of values your code can work with.” Use optionals to safely work with possibly missing values: missing values are nil present values are wrapped in an optional
  7. “Swift also introduces optional types, which handle the absence of a value. Optionals say either “there is a value, and it equals x” or “there isn’t a value at all”. Optionals are similar to using nil with pointers in Objective-C, but they work for any type, not just classes.” “Optionals are an example of the fact that Swift is a type safe language. Swift helps you to be clear about the types of values your code can work with.” “Swift’s nil is not the same as nil in Objective-C. In Objective-C, nil is a pointer to a non-existent object. In Swift, nil is not a pointer—it is the absence of a value of a certain type. Optionals of any type can be set to nil, not just object types.”
  8. Optionals say either “there is a value, and it equals x” or “there isn’t a value at all”. Optionals are similar to using nil with pointers in Objective-C, but they work for any type, not just classes.” “Optionals are an example of the fact that Swift is a type safe language. Swift helps you to be clear about the types of values your code can work with.” Use optionals to safely work with possibly missing values: missing values are nil present values are wrapped in an optional
  9. var possibleNumber = "2" if let actualNumber = possibleNumber.toInt() { println("(possibleNumber) has an integer value of (actualNumber)") } else { println("(possibleNumber) could not be converted to an integer") }
  10. Say we have a person -- and people in our domain always have names, but they may not have addresses. So we have the name type as a String, but the address type is an optional Address class. We have this instance method (function) on Address called sendLetter, and we want to send a letter to each person who has an address. DEMO so, if the optional is nil it just swallows the method call. No undefined method for nilclass error.
  11. One of the nice things, I think, about Objective C its verbosity. I like the self-documenting nature of named parameters. Swift is a lot more flexible in that it lets you use named parameters or get rid of them all together, or even use different external param names for callers than the names used within the function definition.
  12. Enumerations define a type for a group of related values and you can work with those values in a type-safe way. Some cool things about enumerations in Swift, is 1) they don’t need member values, unlike in C, North, South, East, West don’t equal 1, 2, 3, or 4 or whatever. Another cool thing is an enumeration can have associated values. So, if you have a Status enum with a status of OnTime and of Delayed -- the Delayed status can have an associated delay of minutes and maybe a string that contains the reason for the delay.
  13. Swift has a really powerful switch statement. It is exhaustive, which means the compiler forces you to check for every possible value for the type that you are checking. Now, if you are switching on integers you don’t have to have a line for ‘n’ to infinity -- you can use the default case.
  14. Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages. One of the coolest things about closures is that closures can capture and store references to any constants and variables from the context in which they are defined. This is known as closing over those constants and variables, hence the name “closures”. Ruby has closures in the form of lambdas and procs, so I don’t really need to say much about them in Swift, other than to show the expression syntax for them in Swift.
  15. struct Stack<T> { var items = T[]() mutating func push(item: T) { items.append(item) } mutating func pop() -> T { return items.removeLast() } } var stack = Stack<String>()