- api calls
- disk I/O
- data preparation
Tag: ios
let vs. read-only (computed)
letmeans constant, and cannot be set after initialized.- read-only also means cannot be set but since it is computed so it could return different value at different times.
2 Swift examples of Decorator Design Pattern
Extension and Delegation
QoS
Note: iOS 8+ should use QoS instead of system default queues (times showed are just examples)
- User-interactive: UI feedback. Such as animation. (<1s)
- User-initiated: UI works that required in order to continue the interaction. Such as opening a file. (1~3s)
- Utility: UI works that have no need for an immediate result. Such as downloading a file. (3s~3m)
- Background: Non-UI works. Such as indexing, backup. (3m~3h)
Location tracking and battery usage
- Visits location service (CLVisit): most power-efficient way. Not for navigation or real-time. Good for doing async background processing related to location. Or to identify location pattern. Requires Always authorization.
- Region monitoring (Geofencing): Define a circular region and your app gets a notification when crossing the boundary. Apple’s built-in Reminder app uses that too. Very little battery consumption. It is built upon Core Location’s significant-change location service. Requires Always authorization.
- Significant-change location service: power-friendly way. Requires Always authorization.
- Standard location service: Real-time. Most power consumption.
When/what/how to cache
When? Read a lot, but no/min updates.
What? Images, API call results, computational results (e.g., row heights).
How? Use NSCache, networking frameworks that supports caching, set cache policy (e.g., NSURLRequest.CachePolicy.returnCacheDataElseLoad).
inout keyword
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() {}
}