The Swift Programming Language
by Parker · 58 things on Twos
- https://books.apple.com/us/book/the-swift-programming-language-swift-5-2/id881256329
- Apple, Inc.
- Modern programming patterns: variables are always initialized before use, array indices are checked for out-of-bounds errors, integers are checked for overflow, optionals ensure that nil values are handled explicitly, memory is managed automatically, error handling allows controlled recovery from unexpected failures
- Code written at global scope is used as the entry point for the program, so you don't need a main() function
- Use let to make a constant and var to make a variable
- A constant or variable must have the same type as the value you want to assign to it
- let explicitDouble: Double = 70
- Values are never implicitly converted to another type
- let widthLabel = label + String(width)
- Write a value in parentheses, and write a blackslash (\) before the parentheses to include values in strings
- let appleSummary = "I have \(apples) apples."
- Use three double quotation marks (""") for strings that take up multiple lines
- Create arrays and dictionaries using brackets ([]), and access their elements by writing the index or key in brackets
- Arrays automatically grow as you add elements: shoppingList.append("blue paint")
- Create an empty array or dictionary with the initializer syntax: let emptyArray = [String]() or let emptyDictionary = [String: Float]()
- An optional value either contains a value or contains nil to indicate that a value is missing
- Write a question mark after the type of a value to mark the value as optional
- You can use if and let together to work with values that might be missing: if let name = optionalName { ... }
- Use the ?? operator to provide a default value to an optional value
- After executing the code inside a switch case that matched; the program exists from the switch statement
- for (key, value) in dictionary { ... }
- for value in array { ... }
- Make a range of indexes: for i in 0..<4 { ... } or i in 0...4
- Use func to declare a function. Call a function by following its name with a list of arguments in parentheses. Use -> to separate the parameter names and types from the function's return type
- Use a tuple to make a compound value—for example, to return multiple values from a function. The elements of a tuple can be referred to either by name or by number
- class NamedShape {
var numberOfSides: Int = 0
var name: String
init(name: String) {
self.name = name
}
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
- Every property of a class needs a value assigned—either in its declaration or in the initializer
- When working with optional values, you can write ? before operations like methods, properties, and subscripting. IF the value before the ? is nil, everything after the ? is ignored and the value of the whole expression is nil
- Use extension to add functionality to an existing type, such as new methods and computed properties
- You can use a protocol name just like any other named type. When you work with values whose type is a protocol type, methods outside the protocol definition are not available
- You represent errors using any type that adopts the Error protocol
- Use throw to throw an error and throws to mark a function that can throw an error. If you throw an error in a function, the function returns immediately and the code that called the function handles the error
- One way to handle errors is with a do-catch block. You can provide multiple catch blocks that handle specific errors
- Another way to handle errors is with try? to convert the result to an options. If the function throws an error, the specific error is discarded and the result is nil. Otherwise, the result is an optional containing the value that the function returned
- Use defer to write a block of code that is executed after all other code in the function, just before the function returns
- Tuples are now available and enable you to create and pass around groupings of values. You can use a tuple to return multiple values from a function as a single compound value
- Optionals say either "there is a value, and it equals x" or "there isn't a value at all"
- You can declare multiple constants or multiple variables on a single line, separated by commas: var x = 0.0, y = 0.0, z = 0.0
- Provide a type annotation when you declare a constant or variable, to be clear about the kind of values the constant or variable can store
- The colon in the declaration means "...of type ..."
- Swift can almost always infer the type based on the initial value for a constant or variable at the point that it's defined
- Use print to print out values: print("Hello") and print(someValue, terminator: "")
- String interpolation: print("The value is \(someValue)")
- Nested multiline comments enables you to comment out large blocks of code quickly and easily, even if the code already contains multiline comments
- You define type aliases with the typealias keyword
- You can't use nil with non-optional constants and variables
- Optional binding: if let constantName = someOptional { ... }
- An implicitly unwrapped optional is a normal optional behind the scenes, but can also be used like a non-optional value, without the need to unwrap the optional value each time it's accessed
- Assertions are checked only in debug builds: assert(check, string)
- ..< and ... are used as a shortcut for expressing a range of values
- Multiline string literals use three double quotation marks
- Use isEmpty property to check if a string is empty
- You can access the individual character values for a string by iterating over the string with a for-in loop
- If a string is empty, startIndex and endIndex properties are equal
- Inserting characters into a string: insert(_:at:) or insert(contentsOf:at:)
- An array stores values of the same type in an ordered list
- Five control transfer statements: continue, break, fallthrough, return, throw
- If #available(iOS 10, macOS 10.12, *) { ... } else { ... }