Mobile Application Development-Android and It’s Tools
Welcome to Swift (CocoaCoder 6/12/14)
1. Welcome to Swift
Carl Brown (@CarlBrwn)
CocoaCoder.org, 12 June 2014 (WWDC Keynote + 10 days)
2. Disclaimer
• We’ve known of this
language’s existence for less
than two weeks
• I’ve yet to ship a project with it
• We’ve been told the language
will be changing over time
*image: http://vectorgoods.com/wp-content/uploads/2012/01/nuclear-danger-vector.jpg
4. What is Swift?
New Programming Language from Apple
Announced at WWDC 2014
After being worked on in secret for 4 years
Interoperates with (and may eventually replace) Objective-C
Currently still a work in progress
5. Looks a lot like a scripting language*
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
println ("the score is (teamScore)")
*but it’s compiled
6. Swift != Obj-C
Goodbye Square Brackets*
!
…and semicolons
*Except Array definitions and subscripts
7. Standard-ish Types
var int1: Int = 30
var float1: Float = 30.5
var bool1: Bool = false
var str1: String = "Hello, playground"
var array1: Array = ["Hi", 40]
var dict1: Dictionary <String,String> = [ "key" : "value"]
9. Swift Still has Immutability
let individualScore = 75
!
!
var teamScore = 0
Read-Only
Read-Write
*Array immutability seems complicated for performance reasons
10. Loops
var firstForLoop = 0
for i in 0..3 {
firstForLoop += i
}
var n = 2
while n < 100 {
n = n * 2
}
var m = 2
do {
m = m * 2
} while m < 100
let individualScores = [75, 43, 12]
for score in individualScores {
teamScore += 3
}
11. Switch directly on Objects
let vegetable = "red pepper"
switch vegetable {
case "celery":
let vegetableComment = "Add some raisins."
case "cucumber", "watercress":
let vegetableComment = "Make a good tea sandwich."
case let x where x.hasSuffix("pepper"):
let vegetableComment = "Is it a spicy (x)?"
default:
let vegetableComment = "Everything okay in soup."
}
*All possibilities MUST be covered or compiler error
12. “Tuples”
let (statusCode, statusMessage) = http404Error
let http404Error = (404, "Not Found")
println("The status code is (statusCode)")
// prints "The status code is 404"
println("The status message is (statusMessage)")
// prints "The status message is Not Found”
*This Excerpt (and many others) From: Apple Inc. “The Swift Programming Language.” iBooks.
14. “Optionals”
Primitive Types can’t be nil
Types have “Optional” versions (nil or value)
You have to “Unwrap” Optionals before you can use them in non-optional
context
15. Convention:
Use “if let” to “Unwrap”
var optionalString: String?
!
if let definiteString = optionalString {
println(definiteString)
}
*You can also use (!) and risk a run-time crash