Simple Values
let
for constants; var
for variables |
Constants: value doesn't need to be known at compile time, but must assign it a value exactly once |
Rule for types: constant or variable must have the same type as the value you want to assign it. |
Inferring Types: Type can be inferred if value provided when creating constant/var. |
Specifying types: Write after the variable, separated by colon |
let explicitDouble: Double = 70
|
Values are never implicitly converted to another type. If conversion required, must be done explicitly |
let lottoString = "Today's winning lotto number is " let lottoNumber = 94 let lottoSentence = lottoString + String(lottoNumber)
|
Backslash string interpolation |
let friendCount = 2 let friendCountString = "I have \(friendCount) number of friends."
|
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. |
var toys = ["labubu", "simski", "furby"] toys[1] = "fuggler" toys.append("jellycat") var bestItemOfThing = [ "summer fruit" : "mango",] bestItemOfThing["summer fruit"] = "peach"
|
Arrays grow automatically. |
For empty array, write excellentFruits = []
. For an empty dictionary, write mediocreFruits = [:]
. |
If assigning empty array or dict to new var, you need to specify type. |
let arrayOfGoodCoffeeCafes: [String] = [] let dictCafesWithMatchaAndRatings: [String: Float] = [:]
|
|
|
Control Flow
Conditionals: if
, switch
|
Loops: for-in
, while
, repeat - while
|
Parentheses around condition/loop variable are optional, braces are required |
let croissantScores = [1.2, 2.3, 2.2, 4] for score in croissantScores { if score > 2.5 { print("Great croissant!!") } }
|
In if
statement, conditional must be a boolean expression. if score { ... }
is an error, not implicit comparison to zero. |
You can assign if conditions to an assignment |
let scoreDecoration = if teamScore > 10 { "🎂" } else { "" } print("Score:", teamScore, scoreDecoration)
|
Optionals: either contains a value or contains nil
to indicate a value is missing. A question mark after type of value marks it as optional. |
var optionalString: String? = "Hello" print(optionalString == nil) // prints "false"
|
Use if
and let
to work with missing values. If optional value is nil
, conditional is false and code in braces is skipped. Otherwise, optional value is unwrapped and assigned to constant after let
, which makes the unwrapped value available inside block of code. |
var optionalName: String? = "Big Dog" var greeting = "Hello!" if let name = optionalName { greeting = "Hello, \(name)" } else { greeting = "Wow!" }
|
??
operator: If optional value missing, default value used instead |
let holidayInNov: String? = nil let holidayInDec: String = "Bali" let welcomeMsg = "Enjoy \(holidayInNov ?? holidayInDec)"
|
Switches: support any kind of data and variety of comparisons |
After executing the code inside the switch case that matched, program exits from the switch statement. Execution doesn't continue to the next case, so you don't need to explicitly break out of the switch at the end of each case's code. |
let perfume = "Eau Rose" switch perfume { case "Electric Cherry": print("Jasmine sambac, ambrettolide musk") case "On a Date", "Born In Roma": print("These have a black currant note.") case let x where x.hasSuffix("rose"): print("Is it a fragrance with \(x)?") default: print("A delicious choice.") } // Prints "Is it a fragrance with rose?"
|
for-in
: Use to iterate over items in a dict by providing pair of names for each key-value pair. |
let interestingNumbers = [ "country codes from my holidays": [66, 1, 86, 82, 45], "cricket players": [49, 56, 26, 30], ] var largest = 0 for (_, numbers) in interestingNumbers { for number in numbers { if number > largest { largest = number } } }
|
|