Avatar
class TaskContext<T: AnyObject> { private weak var weakValue: T? var value: T { get throws { guard let value = weakValue else { throw CancellationError() } return value } } init(weakValue: T?) { self.weakValue = weakValue } } extension Task where Failure == Error { @discardableResult init<T>(priority: TaskPriority? = nil, context: T, operation: @Sendable @escaping (TaskContext<T>) async throws -> Success) { let taskContext = TaskContext(weakValue: context) self.init(priority: priority, operation: { try await operation(taskContext) }) } } こういうのを作っておく するとこうなる Task(context: self) { context in for await foo in try context.value.observe(keyPath: \.foo) { try context.value.printFoo(foo) } } (edited)
3:31 PM
書き味はめちゃくちゃいいね