我有一个UserDefaults
类,用于处理存储、删除和获取存储对象的默认值。这是完整的课程,整洁而简单,我相信:
现在的问题在于存储函数。我似乎无法对Encodable
String
对象进行编码。我知道我可以将该对象存储为默认值,但这会破坏处理通用对象的MVDefaults
的目的。
我在这里错过了什么吗?
import Foundation
enum MVDefaultsKey: String {
case requestToken = "defaultsRequestToken"
}
/// The class that has multiple class functions for handling defaults.
/// Also has the helper class functions for handling auth tokens.
class MVDefaults {
// MARK: - Functions
/// Stores token.
class func store<T: Encodable>(_ object: T, key: MVDefaultsKey) {
let encoder = JSONEncoder()
let encoded = try? encoder.encode(object)
UserDefaults.standard.set(encoded, forKey: key.rawValue)
}
/// Removes the stored token
class func removeDefaultsWithKey(_ key: MVDefaultsKey) {
UserDefaults.standard.removeObject(forKey: key.rawValue)
}
/// Returns stored token (optional) if any.
class func getObjectWithKey<T: Decodable>(_ key: MVDefaultsKey, type: T.Type) -> T? {
guard let savedData = UserDefaults.standard.data(forKey: key.rawValue) else {
return nil
}
let object = try? JSONDecoder().decode(type, from: savedData)
return object
}
}
为 JSON 的字符串"hello"
会是什么样子。它看起来像:
"hello"
不会吧?
这不是一个有效的JSON(根据这里(!不能将字符串直接编码为 JSON,也不能直接解码字符串。
例如,此代码
let string = try! JSONDecoder().decode(String.self, from: ""hello"".data(using: .utf8)!)
将产生错误
JSON 文本未以数组或对象开头,并且未设置允许片段的选项。
和
let data = try! JSONEncoder().encode("Hello")
将产生错误:
编码为字符串 JSON 片段的顶级字符串。
这里的解决方法只是使用 UserDefaults
提供的专用set
方法来存储字符串。但是,您仍然可以使用泛型方法,只需检查类型和强制转换:
if let str = object as? String {
UserDefaults.standard.set(str, forKey: key)
} else if let int = object as? Int {
...
虽然 Sweeper 的评论很有帮助并且应该是答案(因为没有他的,我将无法得出自己的答案(,但我仍然会继续分享我对 Defaults 类所做的工作,使其处理非 JSON 编码对象(例如字符串、整数、数组等(。
在这里:
MVDefaults.swift
import Foundation
enum MVDefaultsKey: String {
case requestToken = "defaultsRequestToken"
case someOtherKey = "defaultsKeyForTests"
}
/// The class that has multiple class functions for handling defaults.
/// Also has the helper class functions for handling auth tokens.
class MVDefaults {
// MARK: - Functions
/// Stores object.
class func store<T: Encodable>(_ object: T, key: MVDefaultsKey) {
let encoder = JSONEncoder()
let encoded = try? encoder.encode(object)
if encoded == nil {
UserDefaults.standard.set(object, forKey: key.rawValue)
return
}
UserDefaults.standard.set(encoded, forKey: key.rawValue)
}
/// Removes the stored object
class func removeDefaultsWithKey(_ key: MVDefaultsKey) {
UserDefaults.standard.removeObject(forKey: key.rawValue)
}
/// Returns stored object (optional) if any.
class func getObjectWithKey<T: Decodable>(_ key: MVDefaultsKey, type: T.Type) -> T? {
if let savedData = UserDefaults.standard.data(forKey: key.rawValue) {
let object = try? JSONDecoder().decode(type, from: savedData)
return object
}
return UserDefaults.standard.object(forKey: key.rawValue) as? T
}
}
这是我为测试默认方法编写的测试(规范(。都过去了!✅
MVDefaultsSpec.swift
@testable import Movieee
import Foundation
import Quick
import Nimble
class MVDefaultsSpec: QuickSpec {
override func spec() {
describe("Tests for MVDefaults") {
context("Tests the whole MVDefaults.") {
it("tests the store and retrieve function for any Codable object") {
let data = stubbedResponse("MovieResult")
expect(data).notTo(beNil())
let newMovieResult = try? JSONDecoder().decode(MovieResult.self, from: data!)
MVDefaults.store(newMovieResult, key: .someOtherKey)
let retrievedObject = MVDefaults.getObjectWithKey(.someOtherKey, type: MovieResult.self)
// Assert
expect(retrievedObject).notTo(beNil())
// Assert
expect(retrievedObject?.movies?.first?.id).to(equal(newMovieResult?.movies?.first?.id))
}
it("tests the store and retrieve function for String") {
let string = "Ich bin ein Berliner"
MVDefaults.store(string, key: .someOtherKey)
let retrievedObject = MVDefaults.getObjectWithKey(.someOtherKey, type: String.self)
// Assert
expect(retrievedObject).notTo(beNil())
// Assert
expect(retrievedObject).to(equal(string))
}
it("tests the removal function") {
MVDefaults.removeDefaultsWithKey(.someOtherKey)
let anyRetrievedObject = UserDefaults.standard.object(forKey: MVDefaultsKey.someOtherKey.rawValue)
let stringRetrievedObject = MVDefaults.getObjectWithKey(.someOtherKey, type: String.self)
// Assert
expect(anyRetrievedObject).to(beNil())
// Assert
expect(stringRetrievedObject).to(beNil())
}
it("tests the store and retrieve function for Bool") {
let someBool: Bool = true
MVDefaults.store(someBool, key: .someOtherKey)
let retrievedObject = MVDefaults.getObjectWithKey(.someOtherKey, type: Bool.self)
// Assert
expect(retrievedObject).to(equal(someBool))
// Assert
expect(retrievedObject).notTo(beNil())
}
}
}
}
}