ParseSwift:如何声明一个 [String: Any]? 属性 对于 ParseObject?

ParseSwift: how to declare a [String: Any]? property for a ParseObject?

我正在尝试使用 Parse-Swift SDK,特别是在应用程序数据库中,我有一些字典属性,比如这个:

elements: Dictionary<String, Any>

["test_string": "hello", "test_number": 22.2] // an example of a value for this property

现在我试着在 Swift 中写这个 ParseObject:

导入基金会;导入解析Swift

struct TestObject: ParseObject {
    var objectId: String?
    var createdAt: Date?
    var updatedAt: Date?
    var ACL: ParseACL?
    var originalData: Data?

    var elements: [String: Any]?
}

但是这样做,我得到了这些错误:

Type 'TestObject' does not conform to protocol 'Decodable'

Type 'TestObject' does not conform to protocol 'Hashable'

Type 'TestObject' does not conform to protocol 'Encodable'

Type 'TestObject' does not conform to protocol 'Equatable'

我该怎么办?感谢您的帮助

Any 不是 Codable 意味着它不符合 Codable 协议并且不能使用 JSON 发送到解析服务器为什么编译器会抱怨。

如果您想要类似于 Any 的内容,您可以添加 AnyCodable package via SPM to your project and use the following types: AnyCodable, AnyEncodable, AnyDecodable. See the notes in the documentation and more info here and here。所以你的对象看起来像:

struct TestObject: ParseObject {
    var objectId: String?
    var createdAt: Date?
    var updatedAt: Date?
    var ACL: ParseACL?
    var originalData: Data?

    var elements: [String: AnyCodable]?
}

访问AnyCodableAnyEncodableAnyDecodable的值;您使用 .value 属性 并尝试将其转换为预期的类型。你可以检查ParseSwift test cases for examples。使用你的 TestObject 类型:

var object = TestObject()
object.elements["myKey"] = AnyCodable("My value")
guard let storedValue = object.elements["myKey"]?.value as? String else {
   print("Should have casted to String")
   return
}
print(storedValue) // Should print "My value" to console