SlideShare uma empresa Scribd logo
1 de 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

Mais conteúdo relacionado

Mais procurados

Swiftの関数型っぽい部分
Swiftの関数型っぽい部分Swiftの関数型っぽい部分
Swiftの関数型っぽい部分bob_is_strange
 
How to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftHow to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftGiordano Scalzo
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overviewhesher
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation JavascriptRamesh Nair
 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6FITC
 
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 ComeCory Forsyth
 
Javascript ES6 generators
Javascript ES6 generatorsJavascript ES6 generators
Javascript ES6 generatorsRamesh Nair
 
Stupid Awesome Python Tricks
Stupid Awesome Python TricksStupid Awesome Python Tricks
Stupid Awesome Python TricksBryan Helmig
 
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 editionosfameron
 
Is Haskell an acceptable Perl?
Is Haskell an acceptable Perl?Is Haskell an acceptable Perl?
Is Haskell an acceptable Perl?osfameron
 
... now write an interpreter (PHPem 2016)
... now write an interpreter (PHPem 2016)... now write an interpreter (PHPem 2016)
... now write an interpreter (PHPem 2016)James Titcumb
 
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 languagePawel Szulc
 
Invertible-syntax 入門
Invertible-syntax 入門Invertible-syntax 入門
Invertible-syntax 入門Hiromi Ishii
 
Hello Swift 3/5 - Function
Hello Swift 3/5 - FunctionHello Swift 3/5 - Function
Hello Swift 3/5 - FunctionCody Yun
 
Swift internals
Swift internalsSwift internals
Swift internalsJung Kim
 

Mais procurados (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
 

Destaque

Sparq lreference 1.8-us
Sparq lreference 1.8-usSparq lreference 1.8-us
Sparq lreference 1.8-usAjay Ohri
 
Data Visualization in R
Data Visualization in RData Visualization in R
Data Visualization in RSophia Banton
 
R programming Language , Rahul Singh
R programming Language , Rahul SinghR programming Language , Rahul Singh
R programming Language , Rahul SinghRavi Basil
 
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 tableauEnkitec
 
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)Carl Brown
 
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 2Yusuke Kita
 
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 2016Apigee | Google Cloud
 
Mindbody: A Digital Transformation Story
Mindbody: A Digital Transformation StoryMindbody: A Digital Transformation Story
Mindbody: A Digital Transformation StoryApigee | Google Cloud
 
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 KapoorApigee | Google Cloud
 
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. Natalia Hatalska
 
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 kapoorApigee | Google Cloud
 
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 JourneyApigee | Google Cloud
 
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 ServerlessApigee | Google Cloud
 
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!Apigee | Google Cloud
 
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 JhingranApigee | Google Cloud
 

Destaque (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
 

Semelhante a A Few Interesting Things in Apple's Swift Programming Language

An Introduction to Scala (2014)
An Introduction to Scala (2014)An Introduction to Scala (2014)
An Introduction to Scala (2014)William Narmontas
 
Naïveté vs. Experience
Naïveté vs. ExperienceNaïveté vs. Experience
Naïveté vs. ExperienceMike Fogus
 
Think sharp, write swift
Think sharp, write swiftThink sharp, write swift
Think sharp, write swiftPascal Batty
 
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 2Kirill Rozov
 
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# 7Paulo Morgado
 
NUS iOS Swift Talk
NUS iOS Swift TalkNUS iOS Swift Talk
NUS iOS Swift TalkGabriel Lim
 
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 wereldWerner Hofstra
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecLoïc Descotte
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlinThijs Suijten
 
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.pdfAndrey Breslav
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlinThijs Suijten
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to PerlSway Wang
 
Exploring Koltin on Android
Exploring Koltin on AndroidExploring Koltin on Android
Exploring Koltin on AndroidDeepanshu Madan
 

Semelhante a 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
 

Mais de SmartLogic

Writing Game Servers with Elixir
Writing Game Servers with ElixirWriting Game Servers with Elixir
Writing Game Servers with ElixirSmartLogic
 
All Aboard The Stateful Train
All Aboard The Stateful TrainAll Aboard The Stateful Train
All Aboard The Stateful TrainSmartLogic
 
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 IvovichSmartLogic
 
Monitoring Your Elixir Application with Prometheus
Monitoring Your Elixir Application with PrometheusMonitoring Your Elixir Application with Prometheus
Monitoring Your Elixir Application with PrometheusSmartLogic
 
Going Multi-Node
Going Multi-NodeGoing Multi-Node
Going Multi-NodeSmartLogic
 
Kubernetes and docker
Kubernetes and dockerKubernetes and docker
Kubernetes and dockerSmartLogic
 
Serializing Value Objects-Ara Hacopian
Serializing Value Objects-Ara HacopianSerializing Value Objects-Ara Hacopian
Serializing Value Objects-Ara HacopianSmartLogic
 
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 EllerbrockSmartLogic
 
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, SmartLogicSmartLogic
 
How SmartLogic Uses Chef-Dan Ivovich
How SmartLogic Uses Chef-Dan IvovichHow SmartLogic Uses Chef-Dan Ivovich
How SmartLogic Uses Chef-Dan IvovichSmartLogic
 
Effective ActiveRecord
Effective ActiveRecordEffective ActiveRecord
Effective ActiveRecordSmartLogic
 
An Introduction to Reactive Cocoa
An Introduction to Reactive CocoaAn Introduction to Reactive Cocoa
An Introduction to Reactive CocoaSmartLogic
 
iOS Development Methodology
iOS Development MethodologyiOS Development Methodology
iOS Development MethodologySmartLogic
 
CSS Preprocessors to the Rescue!
CSS Preprocessors to the Rescue!CSS Preprocessors to the Rescue!
CSS Preprocessors to the Rescue!SmartLogic
 
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 CapistranoSmartLogic
 
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 CodeSmartLogic
 
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 DevelopmentSmartLogic
 
Android Testing: An Overview
Android Testing: An OverviewAndroid Testing: An Overview
Android Testing: An OverviewSmartLogic
 
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 DevelopmentSmartLogic
 
Logstash: Get to know your logs
Logstash: Get to know your logsLogstash: Get to know your logs
Logstash: Get to know your logsSmartLogic
 

Mais 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
 

Último

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 

Último (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 

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() } }

Notas do Editor

  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>()