Skip to content

Commit 62b0c7f

Browse files
slashmoktoso
andauthored
Add mutating merge method to SpanAttributes (#17)
* Add mutating merge method to SpanAttributes * Update SpanAttributes.merge documentation 📖 Co-authored-by: Konrad `ktoso` Malawski <[email protected]> Co-authored-by: Konrad `ktoso` Malawski <[email protected]>
1 parent be4aadb commit 62b0c7f

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

Sources/Tracing/Span.swift

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -529,6 +529,14 @@ extension SpanAttributes {
529529
}
530530
}
531531

532+
/// Merges the given `SpanAttributes` into these `SpanAttributes` by overwriting values of duplicate keys with those of the
533+
/// `other` attributes.
534+
///
535+
/// - Parameter other: `SpanAttributes` to merge.
536+
public mutating func merge(_ other: SpanAttributes) {
537+
self._attributes.merge(other._attributes, uniquingKeysWith: { _, rhs in rhs })
538+
}
539+
532540
/// - Returns: Number of attributes stored.
533541
public var count: Int {
534542
return self._attributes.count

Tests/TracingTests/SpanTests+XCTest.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ extension SpanTests {
3535
("testSpanAttributesUX", testSpanAttributesUX),
3636
("testSpanAttributesCustomValue", testSpanAttributesCustomValue),
3737
("testSpanAttributesAreIterable", testSpanAttributesAreIterable),
38+
("testSpanAttributesMerge", testSpanAttributesMerge),
3839
("testSpanParentConvenience", testSpanParentConvenience),
3940
]
4041
}

Tests/TracingTests/SpanTests.swift

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,26 @@ final class SpanTests: XCTestCase {
137137
}
138138
}
139139

140+
func testSpanAttributesMerge() {
141+
var attributes: SpanAttributes = [
142+
"0": 0,
143+
"1": true,
144+
"2": "test",
145+
]
146+
let other: SpanAttributes = [
147+
"0": 1,
148+
"1": false,
149+
"3": "new",
150+
]
151+
152+
attributes.merge(other)
153+
154+
XCTAssertEqual(attributes["0"]?.toSpanAttribute(), 1)
155+
XCTAssertEqual(attributes["1"]?.toSpanAttribute(), false)
156+
XCTAssertEqual(attributes["2"]?.toSpanAttribute(), "test")
157+
XCTAssertEqual(attributes["3"]?.toSpanAttribute(), "new")
158+
}
159+
140160
func testSpanParentConvenience() {
141161
var parentBaggage = Baggage.topLevel
142162
parentBaggage[TestBaggageContextKey.self] = "test"

0 commit comments

Comments
 (0)