From 4365b55ba9e5ab3de01b57c6c255eb344caaea5e Mon Sep 17 00:00:00 2001 From: uhooi Date: Sun, 20 Nov 2022 23:18:27 +0900 Subject: [PATCH] Fix Error alert appears at first launch --- .../Core/UserDefaults/UserDefaultsClient.swift | 12 ++++++------ .../Sources/Data/Sakatsu/SakatsuRepository.swift | 8 +++++++- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/TotonoiPackage/Sources/Core/UserDefaults/UserDefaultsClient.swift b/TotonoiPackage/Sources/Core/UserDefaults/UserDefaultsClient.swift index 546a223..4fe59a6 100644 --- a/TotonoiPackage/Sources/Core/UserDefaults/UserDefaultsClient.swift +++ b/TotonoiPackage/Sources/Core/UserDefaults/UserDefaultsClient.swift @@ -4,13 +4,13 @@ public typealias UserDefaultsGettable = Decodable public typealias UserDefaultsSettable = Encodable public typealias UserDefaultsPersistable = UserDefaultsGettable & UserDefaultsSettable -private enum UserDefaultsError: LocalizedError { - case gettingFailed(key: String) +public enum UserDefaultsError: LocalizedError { + case missingValue(key: String) - var errorDescription: String? { + public var errorDescription: String? { switch self { - case .gettingFailed: - return "オブジェクトの取得に失敗しました。" + case .missingValue: + return "対象のキーに値が存在しません。" } } } @@ -26,7 +26,7 @@ public struct UserDefaultsClient { let jsonDecoder = JSONDecoder() jsonDecoder.keyDecodingStrategy = .convertFromSnakeCase guard let data = userDefaults.data(forKey: defaultName) else { - throw UserDefaultsError.gettingFailed(key: defaultName) + throw UserDefaultsError.missingValue(key: defaultName) } return try jsonDecoder.decode(V.self, from: data) } diff --git a/TotonoiPackage/Sources/Data/Sakatsu/SakatsuRepository.swift b/TotonoiPackage/Sources/Data/Sakatsu/SakatsuRepository.swift index 7d4ccee..8c9ceb4 100644 --- a/TotonoiPackage/Sources/Data/Sakatsu/SakatsuRepository.swift +++ b/TotonoiPackage/Sources/Data/Sakatsu/SakatsuRepository.swift @@ -16,7 +16,13 @@ public struct SakatsuUserDefaultsClient { extension SakatsuUserDefaultsClient: SakatsuRepository { public func sakatsus() throws -> [Sakatsu] { - try userDefaultsClient.object(forKey: Self.sakatsusKey) + do { + return try userDefaultsClient.object(forKey: Self.sakatsusKey) + } catch UserDefaultsError.missingValue { + return [] + } catch { + throw error + } } public func saveSakatsus(_ sakatsus: [Sakatsu]) throws {