Use it when you need to pass the reference to a value variable (vs. just the value) into a function.
When to use unowned variable
Only when you want to use a weak variable but are sure it will never be nil once it has been set during initialization.
Capture list/value
Notes from Capturing Values In Swift Closures
Within a closure, referring to variables outside of the closure, strong references are created.
class MyClass {
let a = 1
let myClosure = {
print(self.a)
}
myClosure() // 1
a = 2
myClosure() // 2
}
If we don’t want the strong ref, we can specify weak
class MyClass {
let a = 1
let myClosure = { [weak self] in
guard let strongSelf = self else { return }
print(strongSelf.a)
}
myClosure() // 1
a = 2
myClosure() // 1 <-- here's the difference
}
Swift Singleton
Nice article says it all.
class MySingleton {
static let sharedInstance = MySingleton()
private init() {}
}
Match UIImage size to UIImageView
Why? Scaling images on the fly impact performance.
How? If you have no control over the incoming image size, then scale the image outside of the main thread before displaying.
Dispatch Queues
What? A queue that runs tasks FIFO.
Types?
- Serial – one at a time
- system-provided: main queue
- you can create your own
- Concurrent – 1+ tasks at a time
- system-provided: 4 queues (high, default, low, and background)
- you can create your own, but 4 system ones should be good enough
Make use of the reuseIdentifier
For:
UITableViewCellsUICollectionViewCellsUITableViewHeaderFooterViews
If not reuse, it will create one each time a cell is displayed which impacts scrolling performance.
Remember to reuse
- headers and footers
- supplementary views
Set views as Opaque, if possible
Opaque means no transparency defined. If not set, it will impact performance, especially the animated UIs.
Why? iOS needs to go deeper into the view hierarchy to figure out what color to render.
How? Use Debug\Color Blended Layers option to locate non-opaque views.
NSError
Notes from NSError
domain: the subsystemcode: error code within that subsystemuserInfo: a dictionary, contains all other details
Also available: localizedDescription
Defer keyword
Run the block of code before leaving the current scope. Similar to “finally” in other language’s try/catch block.