Cheat sheet
Function that accepts a parameter
/// Functions have triple-slash comments.
///
/// Parameters:
/// - paramA: description of what this is used for.
/// - paramB: description of what this other one is for.
func myFunction(paramA: Int, paramB: Int) {
// Code here uses paramA and paramB.
print(paramA + paramB)
}
Parameters can have labels which are used when calling but not used inside the function body. If the label is an _, then no parameter name needs to be specified.
/// Blah blah.
///
/// Parameters:
/// - paramA: if the label is an underscore, use the actual name.
/// - secondNumber: if the label is NOT an underscore, use the label.
func myFunction(_ paramA: Int, secondNumber paramB: Int) {
print(paramA + paramB)
}
// Notice: no paramA at the call site.
// secondNumber instead of paramB.
myFunction(1, secondNumber: 2)
Function that returns a value
A function returning a value passes it to where-ever it was called. You need to use var or let to capture that value or place the call inside another function call, like so:
/// Again, functions have triple-slash comments.
///
/// Returns: description of what gets returned.
func myReturningFunction() -> Int {
// All code paths **must** result in a return.
if condition {
return 0
} else {
return 1
}
}
// Capture a constant.
let constant = myReturningFunction()
// Use in another function call.
print(myReturningFunction())
Function that accepts parameters AND returns a value
Here’s something you might find useful in the test.
/// Asks for user input repeatedly until a valid input is found.
/// The user can cancel using a specified phrase.
///
/// Parameters:
/// - prompt: the question to ask the user.
/// - cancelPhrase: the word or phrase the user can type to cancel.
/// Returns: the user's input as a string or nil if cancelled
func getUserInput(_ prompt: String, cancelPhrase: String) -> String? {
// Loop until either valid input or the cancelPhrase is detected.
while true {
print(prompt, terminator: " ")
// Make sure the input is not nil or empty.
// Otherwise, restart the loop (continue).
guard let userInput = readLine(), userInput.count > 0 else {
continue
}
// If the user entered the cancel phrase, return nil.
guard userInput != cancelPhrase else {
return nil
}
// Finally, we have valid input to return.
return userInput
}
}
2D arrays
Arrays containing arrays have the [[Element]] type, where Element represents the type contained in the array. For example, an array of arrays of Int is [[Int]].
You can create an empty array of arrays by annotating the data type. If you don’t, Swift can’t know what types are allowed to be added to the array and will refuse to compile.
// OK!
var emptyArray: [[Int]] = []
// No way!
var emptyArray = []
To create your own 2D arrays, put new arrays on new lines.
// No annotation needed because the type will be made clear
// from the contents (strings), thus Swift knows the type is
// going to be [[String]].
var seatingPlan = [
["Mel", "Melanie", "Emma", "Geri", "Victoria"],
["Gary", "Howard", "Mark", "Jason", "Robbie"],
["Cheryl", "Nadine", "Sarah", "Nicola", "Kimberley"],
["Kian", "Mark", "Shane", "Nicky". "Brian"],
["Lee", "Claire", "Lisa", "Faye", "H"]
]
Accessing 2D array members
Accessing members of a 2D array requires two subscripts (accesses via square brackets).
Getting a row
let secondRow = seatingPlan[1]
Getting an item in that row
// Either used the row you got...
let secondSeat = secondRow[1]
// Or access directly from the whole array.
// Note the two subscripts: [1] and [2], directly after each other.
let secondRowThirdSeat = seatingPlan[1][2]
Modifying 2D arrays
Inserting an item into a row
You can use .append(_:) or .insert(_:at:), just as with 1D arrays.
// Adding a whole row to the 2D array.
seatingPlan.append(["Michael", "Keith", "Stephen", "Shane"])
// Adding a missing name to beginning of the last row.
seatingPlan[5].append("Ronan", at: 0)
print(seatingPlan[5]) // ["Ronan", "Michael", "Keith", "Stephen", "Shane"]
Removing at item
Similarly, you can use remove(at:) to remove rows or items.
// Removing the whole first row.
seatingPlan.remove(at: 0)
// Removing the third name in the new first row (formerly second).
let name = seatingPlan[0].remove(at: 2)
print(name)