From f538f821e09ae8ede47f6a10bfc211ea1782fd43 Mon Sep 17 00:00:00 2001 From: Dariusz Rybicki <dariusz@elixxir.io> Date: Wed, 7 Sep 2022 23:56:10 +0200 Subject: [PATCH] Add convenient getter & setter to Fact array --- Sources/XXClient/Models/Fact.swift | 14 +++++++ Tests/XXClientTests/Models/FactTests.swift | 45 ++++++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/Sources/XXClient/Models/Fact.swift b/Sources/XXClient/Models/Fact.swift index 2ee8a6b3..f239a86d 100644 --- a/Sources/XXClient/Models/Fact.swift +++ b/Sources/XXClient/Models/Fact.swift @@ -43,3 +43,17 @@ extension Array where Element == Fact { return try JSONEncoder().encode(self) } } + +extension Array where Element == Fact { + public func get(_ type: FactType) -> Fact? { + first(where: { $0.type == type.rawValue }) + } + + public mutating func set(_ type: FactType, _ value: String?) { + removeAll(where: { $0.type == type.rawValue }) + if let value = value { + append(Fact(fact: value, type: type.rawValue)) + sort(by: { $0.type < $1.type }) + } + } +} diff --git a/Tests/XXClientTests/Models/FactTests.swift b/Tests/XXClientTests/Models/FactTests.swift index c844af66..0e777e7d 100644 --- a/Tests/XXClientTests/Models/FactTests.swift +++ b/Tests/XXClientTests/Models/FactTests.swift @@ -51,4 +51,49 @@ final class FactTests: XCTestCase { XCTAssertNoDifference(encodedModels, jsonData) } + + func testArrayGetter() { + let facts = [ + Fact(fact: "username", type: 0), + Fact(fact: "email", type: 1), + Fact(fact: "phone", type: 2), + Fact(fact: "other", type: 3), + ] + + XCTAssertNoDifference( + [ + facts.get(.username), + facts.get(.email), + facts.get(.phone), + facts.get(.other(3)), + facts.get(.other(4)), + ], + [ + Fact(fact: "username", type: 0), + Fact(fact: "email", type: 1), + Fact(fact: "phone", type: 2), + Fact(fact: "other", type: 3), + nil + ] + ) + } + + func testArraySetter() { + var facts: [Fact] = [] + + facts.set(.email, "email") + facts.set(.phone, "phone") + facts.set(.other(3), "other") + facts.set(.username, "username") + + XCTAssertNoDifference( + facts, + [ + Fact(fact: "username", type: 0), + Fact(fact: "email", type: 1), + Fact(fact: "phone", type: 2), + Fact(fact: "other", type: 3), + ] + ) + } } -- GitLab