- Published on
onChange的用法
- Authors
- Name
nonisolated
func onChange<V>(
of value: V,
initial: Bool = false,
_ action: @escaping (V, V) -> Void
) -> some View where V : Equatable
SwiftUI/View/onChange(of:initial:_:)
Adds a modifier for this view that fires an action when a specific value changes.
Parameters
Value
The value to chack against when determining whether to run the closure.
initial
whether the action should be run when this view initially appears.
action A closure to run when the value changes.
Return Value
A view that fires an aciton when the specified value chagnes.
Discussion
You can use onChange to trigger a side effect as the result of a value changing, such as an Environment key or a Binding.
The system may call the action closure on the main actor, so avoid long-running tasks in the closure. If you need to perform such tasks, detach an asynchronous background task.
When the value changes, the new version of the closure will be called, so any captured values will have their values from the time that the observed value has its new value. The old and new observed values are passed into the closure. In the following code example, PlayerView passes both the old and new values to the model.
nonisolated
https://www.swift.org/blog/swift-6.1-released/
Swift's concurrency model allows writing nonisolated
on properties and functions to indicate that an API is safe to call from any concurrent context. Swift 6.1 extends nonisolated
to types and extensions. This allows you to write nonisolated
to prevent @MainActor
inference on a type, or to apply nonisolated
to all methods in an extension without having to annotate every method:
@MainActor
struct S {
let id: Int
let name: String
//mutable state and MainActor methods
}
nonisolated extension S: CustomStringConvertible, Equatable {
var description: String {
"id: \(id), name: \(name)"
}
static func ==(lhs: S, rhs: S) -> Bool {
lhs.id == rhs.id
}
}
SE-313 introduced the nonisolated
and isolated
keywords as part of adding actor isolation control. Actors are a new way of providing synchronization for shared mutable states with the new concurrency framework