TransactionKey
A key for accessing values in a transaction.
Declaration
protocol TransactionKeyOverview
You can create custom transaction values by extending the Transaction structure with new properties. First declare a new transaction key type and specify a value for the required defaultValue property:
private struct MyTransactionKey: TransactionKey {
static let defaultValue = false
}The Swift compiler automatically infers the associated Value type as the type you specify for the default value. Then use the key to define a new transaction value property:
extension Transaction {
var myCustomValue: Bool {
get { self[MyTransactionKey.self] }
set { self[MyTransactionKey.self] = newValue }
}
}Clients of your transaction value never use the key directly. Instead, they use the key path of your custom transaction value property. To set the transaction value for a change, wrap that change in a call to withTransaction:
withTransaction(\.myCustomValue, true) {
isActive.toggle()
}To use the value from inside MyView or one of its descendants, use the transaction(_:) view modifier:
MyView()
.transaction { transaction in
if transaction.myCustomValue {
transaction.animation = .default.repeatCount(3)
}
}