This document summarizes various Swift concepts including collection types like arrays and dictionaries, mutability, accessing and modifying collections, control flow statements like for-in loops and conditional statements, functions like defining parameters and return values, and function types.
7. Accessing and
Modifying an Array
• shoppingList[0] = “Six Eggs”
• shoppingList[4…6] = [“Bananas”, “Apples”]
• shoppingList.insert(“Maple Syrup”,
atIndex: 0)
• let mapleSyrup =
shoppingList.removeAtIndex(0)
• let apples = shoppingList.removeLast()
8. Iterating Over an
Array
• for item in shoppingList {
println(item)
}
• for (index, value) in
enumerate(shoppingList) {
println(“(index+1): (value)”)
}
9. Creating and
Initializing an Array
• var someInts = [Int]()
someInts.append(3)
someInts = []
• var threeDoubles = [Double](count: 3,
repeatedValue: 0.0)
• var anotherThreeDoubles = Array(count: 3,
repeatedValue: 2.5)
• var sixDoubles = threeDoubles +
anotherThreeDoubles
11. Accessing and
Modifying a Dictionary
• airports.count
• airports[“LHR”] = “London”
• airports[“LHR”] = “London Heathrow”
12. Accessing and
Modifying a Dictionary
• if let oldValue =
airports.updateValue(“Dublin
International”, forKey: “DUB”) {
println(oldValue)
}
• if let airportName = airports[“DUB”] {
println(airportName)
} else {
println(“not in the airports”)
}
13. Accessing and
Modifying a Dictionary
• airports[“APL”] = “Apple
International”
airports[“APL”] = nil
• if let removedValue =
airports.removeValueForKey(“DUB”) {
println(“removed (removedValue)”)
} else {
println(“not contain a value”)
}
14. Iterating Over a
Dictionary
• for (airportCode, airportName) in
airports {
println(“(airportCode):
(airportName)”)
}
• for airportCode in airports.keys
• for airportName in airports.values
15. Creating an Empty
Dictionary
• var namesOfIntegers = [Int: String]()
namesOfIntegers[16] = “sixteen”
namesOfIntegers = [:]
16. Hash Values for
Dictionary Key Types
• A type must be hashable in order to
be used as a dictionary’s key type —
that is, the type must provide a way
to compute a hash value for itself.
20. Conditional Statements
• var temperatureInFahrenheit = 30
if temperatureInFahrenheit <= 32 {
println(“It’s very cold.
Consider wearing a scarf.”)
}
21. Conditional Statements
• var temperatureInFahrenheit = 40
if temperatureInFahrenheit <= 32 {
println(“It’s very cold.
Consider wearing a scarf.”)
} else {
println(“It’s not that cold.
Wear a t-shirt.”)
}
22. Conditional Statements
• var temperatureInFahrenheit = 90
if temperatureInFahrenheit <= 32 {
println(“It’s very cold. Consider
wearing a scarf.”)
} else if temperatureInFahrenheit >= 86 {
println(“It’s really warm. Don’t
forget to wear sunscreen.”)
} else {
println(“It’s not that cold. Wear a
t-shirt.”)
}
23. Conditional Statements
• var temperatureInFahrenheit = 72
if temperatureInFahrenheit <= 32 {
println(“It’s very cold.
Consider wearing a scarf.”)
} else if temperatureInFahrenheit >=
86 {
println(“It’s really warm. Don’t
forget to wear sunscreen.”)
}
24. Switch
• switch some value to consider {
case value 1:
respond to value 1
case value 2,
value 3:
respond to value 2 or 3
default:
otherwise, do something else
}
25. No Implicit
Fallthrough
• switch anotherCharacter {
case “a”:
case “A”:
println(“The letter A”)
default:
println(“Not the letter A”)
}
// this will report a compile-time
error
26. No Implicit
Fallthrough
• switch anotherCharacter {
case “a”, “A”:
println(“The letter A”)
default:
println(“Not the letter A”)
}
• use the fallthrough keyword
27. Range Matching
• switch count {
case 0:
naturalCount = “no”
case 1…3:
naturalCount = “a few”
case 4…9:
naturalCount = “several”
case 10…99:
naturalCount = “tens of”
case 100…999:
naturalCount = “hundreds of”
case 1000…999_999:
naturalCount = “thousands of”
default:
naturalCount = “millions and millions of”
}
28. Tuples
• let somePoint = (1,1)
switch somePoint {
case (0,0):
println(“at the origin”)
case (_,0):
println(“on the x-axis”)
case (0,_):
println(“on the y-axis”)
case (-2…2,-2…2):
println(“inside the box”)
default:
println(“outside of the box”)
}
29. Value Bindings
• var anotherPoint = (2,0)
switch anotherPoint {
case (let x, 0):
println(“on the x-axis an x value of
(x)”)
case (0, let y):
println(“on the y-axis an y value of
(y)”)
case let (x,y):
println(“somewhere else at ((x),
(y))”)
}
30. Where
• let yetAnotherPoint = (1,-1)
switch yetAnotherPoint {
case let (x,y) where x == y:
println(“on the line x == y”)
case let (x,y) where x == -y:
println(“on the line x == -y”)
case let (x,y):
println(“just some arbitrary
point”)
}
32. Fallthrough
• let integerToDescribe = 5
switch integerToDescribe {
case 2,3,5,7,11,13,17,19:
description += " a prime number,
and also”
fallthrough
default:
description += “ an integer.”
}
42. Variadic Parameters
• func arithmeticMean(numbers: Double…) -
> Double {
var total: Double = 0
for number in numbers {
total += number
}
return total / Double(number.count)
}
arithmeticMean(1, 2, 3, 4, 5)
arithmeticMean(3, 8, 19)
43. Constant and Variable
Parameters
• func alignRight(var string: String, count: Int, pad:
Character) -> String {
let amountToPad = count - countElements(string)
if amountToPad < 1 {
return string
}
for _ in 1…amountToPad {
string += pad + string
}
return string
}
let originalString = “hello”
let paddedString = alignRight(originalString, 10, “-”)
44. In-Out Parameters
• func swapTwoInts(inout a: Int, inout
b: Int) {
let temporaryA = a
a = b
b = temporaryA
}
var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt)
45. Function Types
• func addTwoInts(a: Int, b: Int) ->
Int { return a + b }
func multiplyTwoInts(a: Int, b: Int)
-> Int { return a * b }
// (Int, Int) -> Int
• func printHelloWorld() {
println(“hello, world”)
}
// () -> ()
46. Using Function Types
• var mathFunction: (Int, Int) -> Int
= addTwoInts
println(mathFunction(2,3))
• mathFunction = multiplyTwoInts
println(mathFunction(2,3))
• let anotherMathFunction = addTwoInts
47. Function Types as
Parameter Types
• func printMathResult(mathFunction:
(Int, Int) -> Int, a: Int, b: Int) {
println(“Result:
(mathFunction(a,b))”)
}
printMathResult(addTwoInts,3,5)
// prints “Result: 8”
48. Function Types as
Return Types
• func stepForward(input: Int) -> Int {
return input + 1
}
func stepBackward(input: Int) -> Int {
return input - 1
}
func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
return backwards ? stepBackward : stepForward
}
let moveNearerToZero = chooseStepFunction(currentValue > 0)
// blah blah
currentValue = moveNearerToZero(currentValue)