我在下面的
swift 5.10
中编写了代码,通过在下标中给出键值来存储和检索UserDefaults中的可编码数据,但是存在一些编译时错误Expected '->' for subscript element type
import Foundation
extension UserDefaults {
private func setValue<E: Encodable>(_ object: E?, forKey key: String) throws {
if object == nil {
return removeObject(forKey: key)
}
let data = try JSONEncoder().encode(object)
self.set(data, forKey: key)
}
private func object<D: Decodable>(forType type: D.Type, forKey key: String) throws -> D? {
guard let data = self.data(forKey: key) else {return nil}
return try JSONDecoder().decode(D.self, from: data)
}
public subscript<C: Codable>(key: String) (throws) -> C? {
get {
return try object(forType: C.self, forKey: key)
} set {
try setValue(newValue, forKey: key)
}
}
}
下面编写的代码是简单的示例,说明如果没有此错误,它应该如何工作
struct Person: Codable {
var name: String
var age: Int
}
// Storing a Codable object
let person = Person(name: "Alice", age: 30)
do {
try UserDefaults.standard["person"] = person
} catch {
print("Error storing person:", error)
}
// Retrieving a Codable object
do {
if let storedPerson: Person = try UserDefaults.standard["person"] {
print("Retrieved person:", storedPerson)
} else {
print("No person object found in UserDefaults")
}
} catch {
print("Error retrieving person:", error)
}
您可以将 getter 标记为
throws
:
public subscript<C: Codable>(key: String) -> C? {
get throws {
return try object(forType: C.self, forKey: key)
}
}
但是从 Swift 6.0 开始,setter 不能抛出错误。
您有几个选择:
setValue
方法。事实上,我会将其分为 setValue
和 removeValue
方法。fatalError()
assertionFailure()
,它是上述两个选项的组合。调试时使程序崩溃,但对优化构建不执行任何操作。