为 ARAnchor 实现 Codable:“不能在扩展中自动合成......”

gar*_*ing 3 augmented-reality swift arkit codable

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

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

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

rpe*_*cka 7

您可以创建一个容器对象来实现Codable,然后使用它来编码和解码锚点。我在操场上试过这段代码,它对我有用。您需要根据您想要从锚点获取的数据对其进行调整;例如,我进行了编码,name但这对您来说可能没用,如果您的锚点是在没有名称的情况下初始化的,它甚至可能会中断。你也可以用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)
}
Run Code Online (Sandbox Code Playgroud)


Ger*_*eon 5

Swift 编译器 AFAICT 目前不支持在不同的源文件中合成符合Codable,EquatableHashable。有关跟踪此问题的问题,请参阅https://bugs.swift.org/browse/SR-6101