Thanks, clear.
But it seems that an Array<Array<T>>
where T is encodable cannot be declared as Codable. Or at least, it requires initializers for coding(from) and to.
In fact I get an error
Fatal error: Array<Cell> does not conform to Encodable because Cell does not conform to Encodable.: file /BuildRoot/Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-900.0.72/src/swift/stdlib/public/core/Codable.swift, line 3962
where Cell is defined as :
typealias MySet = Set<Int>
struct Cell: Codable {
var classesEntieres : MySet = []
var classesDemiA : MySet = []
var classesDemiB : MySet = []
var m : Int = -1
var s : Int = -1
var a : Int = -1
}
Fail occurs here (names have been edited):
typealias DoubleArray = Array<Array<Cell>>
struct AStruct: Codable {
var tt : Array<Array<Cell>> = []
enum CodingKeys: String, CodingKey {
case tt = "theKey"
}
init(withT : DoubleArray) {
self.tt = withT
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.tt = try values.decode(Array<Array<Cell>>.self, forKey: .tt)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.tt, forKey: .tt) // FAILURE HERE
}
}
The encode is called from try archiver.encodeEncodable:
let valueToSave = DoubleArray()
let data = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWith: data)
do {
try archiver.encodeEncodable(valueToSave, forKey: "theKey") // I use the same string, but is it the same key ?
}
catch {
Swift.print("Unable to encodeEncodable", error)
}
I see no other reason for Cell does not conform to Encodable but an issue with Set ? Or am I totally misusing Codable in link with archiver ?
Note: I saw in Swift.org h ttps://github.com/apple/swift/blob/master/stdlib/public/core/Codable.swift
an extension for sets, but cannot use it yet.
extension Set : Encodable where Element : Encodable {
@_inlineable // FIXME(sil-serialize-all)
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
for element in self {
try container.encode(element)
}
}
}
extension Set : Decodable where Element : Decodable {
@_inlineable // FIXME(sil-serialize-all)
public init(from decoder: Decoder) throws {
self.init()
var container = try decoder.unkeyedContainer()
while !container.isAtEnd {
let element = try container.decode(Element.self)
self.insert(element)
}
}
}
I am trying to upgarde to 9.2 (not beta) to see if there is a difference)
EDITED : tested with XCode 9.2 (9C40b), no difference. So problem is in my code.