From ca18dc409491325ac0875964e5fbf1191a2b57df Mon Sep 17 00:00:00 2001 From: Andriy Date: Thu, 13 Jun 2024 15:17:51 +0300 Subject: [PATCH] feat: add function returning all keys from store --- .../UserDefaultsStore/UserDefaultsStore.swift | 8 ++++++++ .../UserDefaultsStoreTests.swift | 20 +++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/Sources/UserDefaultsStore/UserDefaultsStore.swift b/Sources/UserDefaultsStore/UserDefaultsStore.swift index 59b4bf5..1fab38d 100644 --- a/Sources/UserDefaultsStore/UserDefaultsStore.swift +++ b/Sources/UserDefaultsStore/UserDefaultsStore.swift @@ -106,6 +106,14 @@ public struct UserDefaultsStore: UserDefaultsStoreProtocol { } // MARK: - Data Management + + /// Returns all keys which are present in the store. + /// + /// - Returns: The array of `String` representing all keys from the store. + public func keys() -> [String] { + let keys = userDefaults.dictionaryRepresentation().keys + return [String](keys) + } /// Removes the value associated with a given key. /// diff --git a/Tests/UserDefaultsStoreTests/UserDefaultsStoreTests.swift b/Tests/UserDefaultsStoreTests/UserDefaultsStoreTests.swift index 7f9c039..359960e 100644 --- a/Tests/UserDefaultsStoreTests/UserDefaultsStoreTests.swift +++ b/Tests/UserDefaultsStoreTests/UserDefaultsStoreTests.swift @@ -97,6 +97,26 @@ final class UserDefaultsStoreTests: XCTestCase { XCTAssertTrue(storageValue.isEmpty) } + /// Tests retrieving array containing all keys of the store + func testKeys() throws { + let store = createStore() + + let value1 = "foo" + let key1 = "KEY_1" + store.set(value1, forKey: key1) + + let value2 = "bar" + let key2 = "KEY_2" + store.set(value2, forKey: key2) + + let keys = store.keys() + XCTAssertTrue(keys.contains(key1)) + XCTAssertTrue(keys.contains(key2)) + + let key3 = "KEY_3" + XCTAssertFalse(keys.contains(key3)) + } + /// Tests removing a specific key-value pair. func testRemove() throws { let store = createStore()