Combine
Combine schedulers .receive
and .subscribe
Combine allows for publishers to specify the scheduler used when either receiving from an upstream publisher (in the case of operators), or when sending to a downstream subscriber. This is critical when working with a subscriber that updates UI elements, as that should always be called on the main thread.
1 | somePublisher |
Future
with Deferred
If you want your Future
to act more like Rx’s Single
by having it defer its execution until it receives a subscriber, and having the work execute every time you subscribe you can wrap your Future
in a Deferred
publisher. Let’s expand the previous example a bit to demonstrate this:
1 | func createFuture() -> AnyPublisher<Int, Never> { |
source: https://www.donnywals.com/using-promises-and-futures-in-combine/
SwiftUI
Aligning with .alignmentGuide
To make for example one text align to the left and one to the right within a container, you can use alignmentGuide
as below.
1 | VStack(alignment: .leading) { |
source: https://www.hackingwithswift.com/books/ios-swiftui/alignment-and-alignment-guides
Initialize @State
from initializer
SwiftUI doesn’t allow you to change @State
in the initializer but you can initialize it.
Remove the default value and use _valueName
to set @State
directly instead of going through the property wrapper accessor.
1 | @State var fullText: String // No default value of "" |
source: https://stackoverflow.com/a/58137096
Async code. DispatchQueue
Use DispatchQueue to print something after 1 second
1 | DispatchQueue.main.asyncAfter(deadline: .now() + 1) { |
Timer
Basic usage of scheduled timer
1 | var runCount = 0 |
Example of using Timer within SwiftUI’s ObservableObject
1 | class TimeCounter: ObservableObject { |
Swift language quirks
Self
vs self
When used with a capital S, Self
refers to the type that conform to the protocol, e.g. String
or Int
. When used with a lowercase S, self
refers to the value inside that type, e.g. “hello”
or 556
.
1 | extension BinaryInteger { |
class func
vs static func
functions
Protocols use the class
keyword, but it doesn’t exclude structs from implementing the protocol, they just use static
instead. Class was chosen for protocols so there wouldn’t have to be a third keyword to represent static
or class
. That’s the main difference but some other differences are that class functions are dynamically dispatched and can be overridden by subclasses.
1 | class ClassA { |