Swift Flashcards
Differences Between Classes and Structs
Structs are are accessed as “by value” (using as a param creates a copy) and classes are accessed “by reference” (using as a param passes a pointer).
Classes can inherit from other classes, structs can’t
Which is Better - Class or Struct
Class better for inheritance
Struct better for passing between threads, optimize performance
(FASTER since they are allocated on STACK and classes are allocated on HEAP)
Advantages of Array
Easy access by index
More type-safe (can only contain 1 type of element)
Arrays have many built-in operations (add, remove, filter, sort, etc)
What property is used to allow objects to be serialized/deserialized ?
struct Person: Codable { .. }
All properties need to support codable to be serialized
Then use JsonDecoder()
How to handle custom property names when encoding / decoding to JSON
Use CodingKeys enum
enum CodingKeys: String, CodingKey {
case name = “full_name”
case age
case address
}
What are the 5 different access levels in Swift
open - can be accessed / subclassed
public - accessible but not subclass-able
internal - accessible from same MODULE - DEFAULT LEVEL
fileprivate - accessible from same FILE
private - accessible from same class / struct
What are extensions and why use them
Allow adding new functionality to class / struct (even if source not available)
Group related functionality
Add protocol conformance to a class /struct
Can you add new properties to class/struct using extensions
Stored properties cannot be added
Computed properties can be added
Reason - A TYPES MEMORY LAYOUT IS DETERMINED AT COMPILE TIME
What are associated types ?
Generics for protocols
Why use a protocol ?
interface reusability with different types
Abstraction
Dependency injection - more flexible and testable
Auto Layout
content hugging - when high, view wants to become as SMALL AS POSSIBLE on that axis
compression resistance - when HIGH, the view wants to become AS BIG AS POSSIBLE on that axis
What are size classes
Currently only 2
compact and regular
A device has a size class for each dimension
In Storyboard, you can create ANY, ANY for the default layout and then specific layouts for a particular combination of size classes
UIViewController events (in order)
loadView() - Called before the view is created
viewDidLoad()
viewWillLayoutSubviews()
viewDidLayoutSubviews()
viewWillAppear()
viewDidAppear()
viewWillDisappear()
viewDidDisappear()
Ways to Pass Data Between UIViewControllers
A delegate method - 1 to 1
Post a notification - 1 to many
Dependency injection (params passed when invoked)
Use a closure on the invoked VC
What are different ways to adjust UITableview cell sizes at runtime
tableView: heightForRowAtIndex:
Use self-sizing cells (must have a continuous sequence of constrains from top to bottom). rowHeight = automaticDimension