为什么JSON文本从struct转换为JSON Swift 5后的变量顺序不同于struct

为什么JSON文本从struct转换为JSON Swift 5后的变量顺序不同于struct,json,swift,type-conversion,Json,Swift,Type Conversion,我们想用swift 5创建特定的JSON格式,但我们成功地发现了一个奇怪的错误 这是swift代码 struct Coordinates: Codable { var x: Int var y: Int var width: Int var height: Int } struct Label: Codable { var label: String = "" var coordinates = Coordinate

我们想用swift 5创建特定的JSON格式,但我们成功地发现了一个奇怪的错误

这是swift代码

 struct Coordinates: Codable {
    var x: Int
    var y: Int
    var width: Int
    var height: Int
   }


struct Label: Codable {
    var label: String = ""
    var coordinates = Coordinates(x: 0, y: 0, width: 0, height: 0)
}


struct Annotations: Codable {
    var image = ""
    var annotations :[Label] = [] 
}

var annotations:[Annotations] = []
var label: [Label] = []




func constract(x: CGFloat,
               y: CGFloat,
               w: CGFloat,
               h: CGFloat,
               image: String,
               labell: String,
               imageFileName:String) {
    
    
    
 
    let xx = Int(x)
    let yy = Int(y)
    let ww = Int(w)
    let hh = Int(h)
 

   let coorData = Coordinates(x: xx, y: yy, width: ww, height: hh)

   label.append(Label(label: labell, coordinates: coorData))

   annotations.append(Annotations(image: imageFileName, annotations: label) )

    
   let encoder = JSONEncoder()

   encoder.outputFormatting = .prettyPrinted
    
    
    do {
        

    let data = try encoder.encode(annotations)
     
    print(String(data: data, encoding: .utf8)!)


    } catch {
        print("JSONEncoder error")
    }
} 
这就是结果

 [
  {
    "image" : "0.png",
    "annotations" : [
     {
      "label" : "myImage",
      "coordinates" : {
        "y" : 859,
        "x" : 459,
        "width" : 79,
        "height" : 19
       }
     }
   ]
 }
]

为什么y和x变量的位置不正确?这是虫子吗?还是我遗漏了什么?

您说的是“encoder.encode(annotations)”,所以您对annotations数组进行了编码。奇怪的是,x应该出现在字典定义混乱之前。顺序无关紧要。字典在哪里?我们有struct和JSONIt的基本行为,与Create ML无关。字典值是通过键检索的,而数组中的值是通过索引检索的。