Swift Flashcards
How to label loops?
sum = 0 rowLoop: for row in 0..<8 { columnLoop: for column in 0..<8 { if row == column { continue rowLoop } sum += row * column } }
what is overloading?
When functions have the same name with different parameters.
What is special Never return type in func?
wift that this function will never exit.
func infiniteLoop() -> Never { while true { } }
Writing good functions
The best do /one simple task/, making them easier to mix, match, and model into more complex behaviors.
nil coalescing
??
make an ArraySlice
Use countable ranges
let upcomingPlayersSlice = players[1...2] print(upcomingPlayersSlice[1], upcomingPlayersSlice[2]) // > "Bob Cindy\n"
If you just want to know whether a dictionary has elements or not
is always better to use the isEmpty property. A dictionary needs to loop through all of the values to compute the count. isEmpty, by contrast, always runs in constant time no matter how many values there are
If you want keep the key and set the value to nil
you must use the updateValue method.
dictionary[key] = nil removes the key completely
Rule the hash value
always return the same hash value
When use sets?
If you want to ensure that an item doesn’t appear more than once in your collection, and when the order of your items isn’t important.
Swift Dictionaries
- Are unordered collections of key-value pairs.
The keys are all of the same type, and the values*are all of the same type.
Use subscripting* to get values and to add, update or remove pairs.
- If a key is not in a dictionary, lookup returns nil.
The key of a dictionary must be a type that conforms to the Hashable*protocol.
- Basic Swift types such as String, Int, Double are Hashable out of the box.
Swift Arrays
- Are ordered collections of values of the same type.
Use subscripting*, or one of the many properties and methods, to access and update elements.
- Be wary of accessing an index that’s out of bounds.
Swift closure
Simply a function with no name; you can assign it to a variable and pass it around like any other value.
Closures are so named because they have the ability to “close over” the variables and constants within the closure’s own scope. This simply means that a closure can access, store and manipulate the value of any variable or constant from the surrounding context. Variables and constants used within the body of a closure are said to have been capturedby the closure.
A closure can capture*the variables and constants from its surrounding context.
- A closure can be used to direct how a collection is sorted.
trailing closure syntax
you declare body after other parameters as its body of func, but its body of closure that are inside.
compactMap vs map
This is almost the same as map except it creates an array and tosses out the missing values
Swift character
A Character is grapheme cluster and is made up of one or more code points.
You use special (non-integer) indexes to subscript into the string to a certain grapheme cluster.
rapheme cluster
A Character is grapheme clusterand is made up of one or more code points.
What is character in swift
A Character is grapheme clusterand is made up of one or more code points.
What slicing a string produce?
Slicing a string produce a substring with type Substring, which shares storage with its parent String.
You can convert from a Substring to a String by initializing a new String and passing the Substring.
Structures
They are value types, which means their values are copied on assignment.
Structures are also very /fast/compared to their reference alternatives,
What is faster? Structures or classes? Why?
Structures. Structs rely on the faster stack while classes rely on the slower heap
Stored properties vs computed properties. What have each of them?
Stored properties allocate memory to store a value.
Computed properties are calculated each time your code requests them and aren’t stored as a value in memory.
Do not confuse property observers with getters and setters. A stored property can have a didSet and/or a willSet observer. A computed property has a getter and optionally a setter
read-only computed property vs read-write computed property
read-write computed property: a getter and a setter.
read-only: only getter
lazy modifier
The lazy modifier prevents a value of a stored property from being calculated until your code uses it for the first time. You’ll want to use lazy initializationwhen a property’s initial value is computationally intensive or when you won’t know the initial value of a property until after you’ve initialized the object.
Should I implement this value getter as a method or as a computed property?
Properties hold values that you can get and set, while methods perform work. Sometimes this distinction gets fuzzy when a method’s sole purpose is to return a single value.
memberwise initializer
auto-generated initializer
Methods in structures cannot change the values of the instance without
being marked as mutating -> self is inout in mutating methods.
The heap vs. the stack
When you create a reference type such as class, the system stores the actual instance in a region of memory known as the heap. Instances of a value type such as a struct resides in a region of memory called the stack, unless the value is part of a class instance, in which case the value is stored on the heap with the rest of the class instance.
What is stack?
The system uses the stack to store anything on the immediate thread of execution; it is tightly managed and optimized by the CPU. When a function creates a variable, the stack stores that variable and then destroys it when the function exits. Since the stack is so strictly organized, it’s very efficient, and thus quite fast.
What is heap?
The system uses the heap to store instances of reference types. The heap is generally a large pool of memory from which the system can request and dynamically allocate blocks of memory. Lifetime is flexible and dynamic. The heap doesn’t automatically destroy its data like the stack does; additional work is required to do that. This makes creating and removing data on the heap a slower process, compared to on the stack.
When you create an instance of a class, your code requests a block of memory - where?
on the heap to store the instance itself.
When you create an instance of a struct (that is not part of an instance of a class) where instance is stored?
the instance itself is stored on the stack, and the heap is never involved.
Structure doesn’t have a heap. Heap is classes reference for stack. Structure keeps on stack.
When to use a class versus a struct?
Structs are faster. Structs rely on the faster stack while classes rely on the slower heap.
If you will have many more instances (hundreds and greater), or if these instances will only exist in memory for a short time — lean towards using a struct.
If your data will never change or you need a simple data store, then use structures.
If you need to update your data and you need it to contain logic to update its own state, then use classes.
Use classes when you want reference semantics; structures for value semantics.
Think about comparing. User vs User (class). Address vs Address. (struct)
Often, it’s best to begin with a struct. If you need the added capabilities of a class sometime later, then you just convert the struct to a class.
Equality of structs
instances of value types, which /are/values, are considered equal if they are the same value.
Equality of classes
An objectis an instance of a reference type, and such instances have identitymeaning that every object is unique. No two objects are considered equal simply because they hold the same state. Hence, you use === to see if objects are truly equal and not just containing the same state.