實例方法
assign(to:
assign(to:on:)
將來自發布者的每個元素分配給對象的屬性。
聲明
func assign<Root>(
to keyPath: ReferenceWritableKeyPath<Root, Self.Output>,
on object: Root
) -> AnyCancellable
當
Failure
為 Never
時可用。返回值
AnyCancellable
實例。當您不再希望發布者自動分配屬性時,請在此實例上調用 Cancellable/cancel()
。取消初始化此實例也將取消自動分配。
參數
keyPath
指示要分配的屬性的鍵路徑。請參閱
The Swift Programming Language
中的Key-Path Expression,了解如何使用鍵路徑來指定對象的屬性。object
包含該屬性的對象。訂閱者每次收到新值時都會分配對象的屬性。
詳述
如果您想在每次發布者生成值時設置給定屬性,請使用 Publisher/assign(to:on:)
訂閱者。
在此示例中,Publisher/assign(to:on:)
在 MyClass
的實例上設置 anInt
屬性的值:
class MyClass {
var anInt: Int = 0 {
didSet {
print("anInt was set to: \(anInt)", terminator: "; ")
}
}
}
var myObject = MyClass()
let myRange = (0...2)
cancellable = myRange.publisher
.assign(to: \.anInt, on: myObject)
// Prints: "anInt was set to: 0; anInt was set to: 1; anInt was set to: 2"
可用版本
iOS 13.0+, iPadOS 13.0+, macOS 10.15+, Mac Catalyst 13.0+, tvOS 13.0+, watchOS 6.0+
相關用法
- Swift Result.Publisher assign(to:)用法及代碼示例
- Swift Result.Publisher assertNoFailure(_:file:line:)用法及代碼示例
- Swift Result.Publisher append(_:)用法及代碼示例
- Swift Result.Publisher zip(_:_:_:)用法及代碼示例
- Swift Result.Publisher tryLast(where:)用法及代碼示例
- Swift Result.Publisher sink(receiveCompletion:receiveValue:)用法及代碼示例
- Swift Result.Publisher merge(with:_:_:)用法及代碼示例
- Swift Result.Publisher tryCompactMap(_:)用法及代碼示例
- Swift Result.Publisher print(_:to:)用法及代碼示例
- Swift Result.Publisher sink(receiveValue:)用法及代碼示例
- Swift Result.Publisher eraseToAnyPublisher()用法及代碼示例
- Swift Result.Publisher setFailureType(to:)用法及代碼示例
- Swift Result.Publisher first(where:)用法及代碼示例
- Swift Result.Publisher output(at:)用法及代碼示例
- Swift Result.Publisher tryCatch(_:)用法及代碼示例
- Swift Result.Publisher dropFirst(_:)用法及代碼示例
- Swift Result.Publisher merge(with:_:_:_:_:_:_:)用法及代碼示例
- Swift Result.Publisher flatMap(maxPublishers:_:)用法及代碼示例
- Swift Result.Publisher map(_:_:_:)用法及代碼示例
- Swift Result.Publisher catch(_:)用法及代碼示例
- Swift Result.Publisher drop(while:)用法及代碼示例
- Swift Result.Publisher prefix(_:)用法及代碼示例
- Swift Result.Publisher timeout(_:scheduler:options:customError:)用法及代碼示例
- Swift Result.Publisher merge(with:_:)用法及代碼示例
- Swift Result.Publisher map(_:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 Result.Publisher assign(to:on:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。