Skip to content

Instantly share code, notes, and snippets.

@cyyeh
Last active February 27, 2019 12:04
Show Gist options
  • Select an option

  • Save cyyeh/4703f986d4d9f7624afdd29b8804c464 to your computer and use it in GitHub Desktop.

Select an option

Save cyyeh/4703f986d4d9f7624afdd29b8804c464 to your computer and use it in GitHub Desktop.
Swift Control Flow
/*
Referenced from Stanford CS193p
#: important
##: very important
Control Flow
- For-In Loops
- While Loops
- Conditional Statements
- If
- #Switch
- #No Implicit Fallthrough
- Interval Matching
- Tuples
- Value Bindings
- Where
- Compound Cases
- Control Transfer Statements
- #Break
- Fallthrough
- Early Exit
Reference: https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html
*/
/*
For-In Loops
*/
let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
print("Hello, \(name)!")
}
let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
print("\(animalName)s have \(legCount) legs")
}
for index in 1...5 {
print("\(index) times 5 is \(index * 5)")
}
let base = 3
let power = 10
var answer = 1
for _ in 1...power {
answer *= base
}
print("\(base) to the power of \(power) is \(answer)")
// Prints "3 to the power of 10 is 59049"
let minutes = 60
for tickMark in 0..<minutes {
// render the tick mark each minute (60 times)
print(tickMark)
}
let minuteInterval = 5
for tickMark in stride(from: 0, to: minutes, by: minuteInterval) {
print(tickMark)
// render the tick mark every 5 minutes (0, 5, 10, 15 ... 45, 50, 55)
}
let hours = 12
let hourInterval = 3
for tickMark in stride(from: 3, through: hours, by: hourInterval) {
print(tickMark)
// render the tick mark every 3 hours (3, 6, 9, 12)
}
/*
While Loops
*/
// While
var initialValue = 0
let maxValue = 10
while initialValue < maxValue {
initialValue += 2
print(initialValue)
}
// Repeat-While (do-while)
initialValue = 0
repeat {
initialValue += 2
print(initialValue)
} while initialValue < maxValue
/*
If
*/
var temperatureInFahrenheit = 90
if temperatureInFahrenheit <= 32 {
print("It's very cold. Consider wearing a scarf.")
} else if temperatureInFahrenheit >= 86 {
print("It's really warm. Don't forget to wear sunscreen.")
} else {
print("It's not that cold. Wear a t-shirt.")
}
// Prints "It's really warm. Don't forget to wear sunscreen."
/*
#Switch
*/
let someCharacter = "z"
switch someCharacter {
case "a":
print("The first letter of the alphabet")
case "z":
print("The last letter of the alphabet")
default:
print("Some other character")
}
// Prints "The last letter of the alphabet"
/*
#No Implicit Fallthrough
*/
// To make a switch with a single case that matches both "a" and "A", combine the two values into a compound case, separating the values with commas
let anotherCharacter = "a"
switch anotherCharacter {
case "a", "A":
print("The letter A")
default:
print("Not the letter A")
}
// Prints "The letter A"
/*
Interval Matching
*/
let approximateCount = 62
let countedThings = "moons orbiting Saturn"
var naturalCount = "a"
switch approximateCount {
case 0:
naturalCount = "no"
case 1..<5:
naturalCount = "a few"
case 5..<12:
naturalCount = "several"
case 12..<100:
naturalCount = "dozens of"
case 100..<1000:
naturalCount = "hundreds of"
default:
naturalCount = "many"
}
print("There are \(naturalCount) \(countedThings).")
// Prints "There are dozens of moons orbiting Saturn."
/*
Tuples
*/
let somePoint = (1, 1)
switch somePoint {
case (0, 0):
print("\(somePoint) is at the origin")
case (_, 0):
print("\(somePoint) is on the x-axis")
case (0, _):
print("\(somePoint) is on the y-axis")
case (-2...2, -2...2):
print("\(somePoint) is inside the box")
default:
print("\(somePoint) is outside of the box")
}
// Prints "(1, 1) is inside the box"
/*
Value Bindings
*/
let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
print("on the x-axis with an x value of \(x)")
case (0, let y):
print("on the y-axis with a y value of \(y)")
case let (x, y):
print("somewhere else at (\(x), \(y))")
}
// Prints "on the x-axis with an x value of 2"
/*
Where
*/
let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:
print("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y:
print("(\(x), \(y)) is on the line x == -y")
case let (x, y):
print("(\(x), \(y)) is just some arbitrary point")
}
// Prints "(1, -1) is on the line x == -y"
/*
Compound Cases
*/
var someOtherCharacter: Character = "e"
switch someOtherCharacter {
case "a", "e", "i", "o", "u":
print("\(someOtherCharacter) is a vowel")
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
print("\(someOtherCharacter) is a consonant")
default:
print("\(someOtherCharacter) is not a vowel or a consonant")
}
// Prints "e is a vowel"
let stillAnotherPoint = (9, 0)
switch stillAnotherPoint {
case (let distance, 0), (0, let distance):
print("On an axis, \(distance) from the origin")
default:
print("Not on an axis")
}
// Prints "On an axis, 9 from the origin"
/*
Control Transfer Statements
*/
// continue, break, fallthrough, return, throw
/*
#Break
*/
// Break in a Loop Statement
// Break in a Switch Statement
/*
Fallthrough
*/
let integerToDescribe = 5
var description = "The number \(integerToDescribe) is"
switch integerToDescribe {
case 2, 3, 5, 7, 11, 13, 17, 19:
description += " a prime number, and also"
fallthrough
default:
description += " an integer."
}
print(description)
// Prints "The number 5 is a prime number, and also an integer."
/*
Early Exit
*/
// A guard statement, like an if statement, executes statements depending on the Boolean value of an expression. You use a guard statement to require that a condition must be true in order for the code after the guard statement to be executed. Unlike an if statement, a guard statement always has an else clause—the code inside the else clause is executed if the condition is not true
func greet(person: [String: String]) {
guard let name = person["name"] else {
return
}
print("Hello \(name)!")
guard let location = person["location"] else {
print("I hope the weather is nice near you.")
return
}
print("I hope the weather is nice in \(location).")
}
greet(person: ["name": "John"])
// Prints "Hello John!"
// Prints "I hope the weather is nice near you."
greet(person: ["name": "Jane", "location": "Cupertino"])
// Prints "Hello Jane!"
// Prints "I hope the weather is nice in Cupertino."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment