gpt4 book ai didi

swift - 为 ARAnchor : "cannot be automatically synthesized in an extension..." 实现 Codable

转载 作者:搜寻专家 更新时间:2023-11-01 06:25:39 24 4
gpt4 key购买 nike

代码 extension ARAnchor: Codable {} 产生错误:

“'Decodable' 的实现无法在类型不同的文件的扩展中自动合成”。

这是什么意思?我能够以类似的方式为另一种 native 类型实现 Codable,没有任何错误。

最佳答案

您可以创建一个实现 Codable 的容器对象,然后使用它来编码和解码 anchor 。我在 Playground 上试过这段代码,它对我有用。您需要根据需要从 anchor 获得的数据对其进行调整;例如,我编码了 name 但这对你来说可能没用,如果你的 anchor 是在没有名字的情况下初始化的,它甚至可能会中断。您也可以使用 simd_float4x4 做同样的事情。

import Foundation
import ARKit

class AnchorContainer: Codable {

let anchor: ARAnchor

init(anchor: ARAnchor) {
self.anchor = anchor
}

required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let name = try container.decode(String.self, forKey: .name)
let transform0 = try container.decode(simd_float4.self, forKey: .transform0)
let transform1 = try container.decode(simd_float4.self, forKey: .transform1)
let transform2 = try container.decode(simd_float4.self, forKey: .transform2)
let transform3 = try container.decode(simd_float4.self, forKey: .transform3)
let matrix = simd_float4x4(columns: (transform0, transform1, transform2, transform3))
anchor = ARAnchor(name: name, transform: matrix)
}

func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(anchor.name, forKey: .name) // Might want to make sure that the name is not nil here
try container.encode(anchor.transform.columns.0, forKey: .transform0)
try container.encode(anchor.transform.columns.1, forKey: .transform1)
try container.encode(anchor.transform.columns.2, forKey: .transform2)
try container.encode(anchor.transform.columns.3, forKey: .transform3)
}

enum CodingKeys: String, CodingKey {
case name
case transform0
case transform1
case transform2
case transform3
}

}

// EXAMPLE:

let anchor = ARAnchor(name: "Bill", transform: simd_float4x4(float4(repeating: 4), float4(repeating: 5), float4(repeating: 6), float4(repeating: 7))) // Make a arbitrary anchor
print(anchor) // Figure out what it's value is


do {
let data = try JSONEncoder().encode(AnchorContainer(anchor: anchor))
let anchorDecode = try JSONDecoder().decode(AnchorContainer.self, from: data)
print(anchorDecode.anchor) // Print the value after decoding to make sure that the result is the same
} catch {
print(error.localizedDescription)
}

关于swift - 为 ARAnchor : "cannot be automatically synthesized in an extension..." 实现 Codable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55677651/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com