Browse Source

Enable `Metadata` to be initializable from a `Sequence` of `Elements` (#1871)

Motivation:

This would be a convenient API to have.

Modifications:

Add a new `public init` to `Metadata` which takes `some Sequence<Element>` and initializes `Metadata` collection from the `Sequence` of `Elements`.

Result:

Users can now initialize `Metadata` from a `Sequence` of `Elements`.
Clinton Nkwocha 1 year ago
parent
commit
047cce9f7c
2 changed files with 20 additions and 0 deletions
  1. 7 0
      Sources/GRPCCore/Metadata.swift
  2. 13 0
      Tests/GRPCCoreTests/MetadataTests.swift

+ 7 - 0
Sources/GRPCCore/Metadata.swift

@@ -130,6 +130,13 @@ public struct Metadata: Sendable, Hashable {
     self.elements = []
   }
 
+  /// Initialize `Metadata` from a `Sequence` of `Element`s.
+  public init(_ elements: some Sequence<Element>) {
+    self.elements = elements.map { key, value in
+      KeyValuePair(key: key, value: value)
+    }
+  }
+
   /// Reserve the specified minimum capacity in the collection.
   ///
   /// - Parameter minimumCapacity: The minimum capacity to reserve in the collection.

+ 13 - 0
Tests/GRPCCoreTests/MetadataTests.swift

@@ -17,6 +17,19 @@ import GRPCCore
 import XCTest
 
 final class MetadataTests: XCTestCase {
+  func testInitFromSequence() {
+    let elements: [Metadata.Element] = [
+      (key: "key1", value: "value1"),
+      (key: "key2", value: "value2"),
+      (key: "key3", value: "value3"),
+    ]
+
+    let metadata = Metadata(elements)
+    let expected: Metadata = ["key1": "value1", "key2": "value2", "key3": "value3"]
+
+    XCTAssertEqual(metadata, expected)
+  }
+
   func testAddStringValue() {
     var metadata = Metadata()
     XCTAssertTrue(metadata.isEmpty)