Skip to content

Instantly share code, notes, and snippets.

var stepCount: Int = 0 {
willSet(newSteps) {
print("About to update steps to \(newSteps)")
}
didSet {
if stepCount > oldValue {
print("Added \(stepCount - oldValue) steps")
}
}
}
struct Square {
var sideLength: Double // Stored Property
var area: Double { // Computed Property
get {
return sideLength * sideLength
}
set(newArea) {
sideLength = sqrt(newArea)
}
let temperature = 35
switch temperature {
case let t where t >= 100:
print("Boiling!")
case let t where t <= 0:
print("Freezing!")
default:
print("Liquid state")
}
let point = (2, 0)
switch point {
case (0, 0):
print("At the origin")
case (let x, 0):
print("On the x-axis at \(x)") // Binds the value of '2' to x
case (0, _):
print("On the y-axis") // Ignores the y value
default:
func processOrder(id: Int?) {
guard let orderId = id else {
print("Error: No ID provided.")
return // Must exit scope
}
// orderId is available for the rest of the function!
print("Processing order #\(orderId)")
}
func showProfile(name: String?) {
if let unwrappedName = name {
print("Hello, \(unwrappedName)")
// unwrappedName is only accessible here
}
print("This line runs whether name was nil or not.")
}
let displayedName = userName ?? "Anonymous"
var userName: String? = nil
var displayedName: String
if let name = userName {
displayedName = name
} else {
displayedName = "Anonymous"
}
func swapValues<T>(_ a: inout T, _ b: inout T) {
let temporaryA = a
a = b
b = temporaryA
}
let response = (404, "Not Found") // Inferred as (Int, String)