Skip to content

Commit adbf475

Browse files
committed
add support for attribute appending
1 parent da5743a commit adbf475

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

GrowthBookTests/GrowthBookSDKBuilderTests.swift

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,4 +254,37 @@ class GrowthBookSDKBuilderTests: XCTestCase {
254254

255255
XCTAssertEqual(2, countTrackingCallback)
256256
}
257+
258+
func testAppendAttributes() throws {
259+
let sdkInstance = GrowthBookBuilder(apiHost: testApiHost,
260+
clientKey: testClientKey,
261+
attributes: [:],
262+
trackingCallback: { _, _ in },
263+
refreshHandler: nil,
264+
backgroundSync: false).initializer()
265+
266+
267+
sdkInstance.setAttributes(attributes: ["name": "Alice"])
268+
try sdkInstance.appendAttributes(attributes: ["age": 30])
269+
270+
let result = sdkInstance.gbContext.attributes
271+
XCTAssertEqual(result["name"].stringValue, "Alice")
272+
XCTAssertEqual(result["age"].intValue, 30)
273+
274+
275+
sdkInstance.setAttributes(attributes: ["user": ["id": 1, "name": "Alice"]])
276+
try sdkInstance.appendAttributes(attributes: ["user": ["name": "Bob", "age": 25]])
277+
278+
let user = sdkInstance.gbContext.attributes["user"]
279+
XCTAssertEqual(user["id"].intValue, 1)
280+
XCTAssertEqual(user["name"].stringValue, "Bob")
281+
XCTAssertEqual(user["age"].intValue, 25)
282+
283+
284+
sdkInstance.setAttributes(attributes: ["user": ["roles": ["admin", "editor"]]])
285+
try sdkInstance.appendAttributes(attributes: ["user": ["roles": ["viewer"]]])
286+
287+
let roles = sdkInstance.gbContext.attributes["user"]["roles"].arrayValue.map { $0.stringValue }
288+
XCTAssertEqual(roles, ["admin", "editor", "viewer"])
289+
}
257290
}

Sources/CommonMain/GrowthBookSDK.swift

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,14 @@ public struct GrowthBookModel {
293293
refreshStickyBucketService()
294294
}
295295

296+
/// Merges the provided user attributes with the existing ones.
297+
/// - Throws: `SwiftyJSON.Error.wrongType` if the top-level JSON types differ
298+
@objc public func appendAttributes(attributes: Any) throws {
299+
let updatedAttributes = try gbContext.attributes.merged(with: JSON(attributes))
300+
gbContext.attributes = updatedAttributes
301+
refreshStickyBucketService()
302+
}
303+
296304
@objc public func setAttributeOverrides(overrides: Any) {
297305
attributeOverrides = JSON(overrides)
298306
if gbContext.stickyBucketService != nil {

0 commit comments

Comments
 (0)