Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ AsyncSequences
* [SwitchToLatest](#SwitchToLatest)
* [FlatMapLatest](#FlatMapLatest)
* [HandleEvents](#HandleEvents)
* [Assign](#Assign)
* [EraseToAnyAsyncSequence](#EraseToAnyAsyncSequence)

More operators and extensions are to come. Pull requests are of course welcome.
Expand Down Expand Up @@ -376,6 +377,20 @@ for try await element in handledSequence {}
// finished
```

### Assign

`assign(to:on:)` assigns each element from the async sequence to a property on an object.

```swift
class Root {
var property: String = ""
}

let root = Root()
let fromSequence = AsyncSequences.From(["1", "2", "3"])
try await fromSequence.assign(to: \.property, on: root) // will set the property value to "1", "2", "3"
```

### EraseToAnyAsyncSequence

`eraseToAnyAsyncSequence()` type-erases the async sequence into an AnyAsyncSequence.
29 changes: 29 additions & 0 deletions Sources/Operators/AsyncSequence+Assign.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
//
// AsyncSequence+Assign.swift
//
//
// Created by Thibault Wittemberg on 02/02/2022.
//

public extension AsyncSequence {
/// Assigns each element from the async sequence to a property on an object.
///
/// ```
/// class Root {
/// var property: String = ""
/// }
///
/// let root = Root()
/// let fromSequence = AsyncSequences.From(["1", "2", "3"])
/// try await fromSequence.assign(to: \.property, on: root) // will set the property value to "1", "2", "3"
/// ```
///
/// - Parameters:
/// - keyPath: A key path that indicates the property to assign.
/// - object: The object that contains the property.
func assign<Root>(to keyPath: ReferenceWritableKeyPath<Root, Self.Element>, on object: Root) async throws {
for try await element in self {
object[keyPath: keyPath] = element
}
}
}
29 changes: 29 additions & 0 deletions Tests/Operators/AsyncSequence+AssignTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
//
// AsyncSequence+AssignTests.swift
//
//
// Created by Thibault Wittemberg on 02/02/2022.
//

import AsyncExtensions
import XCTest

private class Root {

var successiveValues = [String]()

var property: String = "" {
didSet {
self.successiveValues.append(self.property)
}
}
}

final class AsyncSequence_AssignTests: XCTestCase {
func testAssign_sets_elements_on_the_root() async throws {
let root = Root()
let sut = AsyncSequences.From(["1", "2", "3"])
try await sut.assign(to: \.property, on: root)
XCTAssertEqual(root.successiveValues, ["1", "2", "3"])
}
}