Say I've defined Position
struct like this:
struct Movement : Codable {
var x: Int
var y: Int
var delay: Int
}
Now I want to pass around [0,0,0]
instead of {"x":0,"y":0,"delay":123}
. How do I define Movement as an array having exactly 3 int values?
I have an API in Swift, it receives a JSON object and needs to move the mouse. At the moment the JSON resembles [{"x":1,"y":2,"delay":123},....]
, I want to instead send [[1,2,123],...]
for this I want to replace the Movement
type with something else.
CodePudding user response:
You could decode it directly into the wanted format
let data = #"[{"x":1,"y":2,"delay":123},{"x":2,"y":2,"delay":25}]"#.data(using: .utf8)!
let array = try! JSONDecoder().decode([[String: Int]].self, from: data)
.map { [$0["x"]!, $0["y"]!, $0["delay"]!]}
This assumes the keys "x", "y" and "delay" always exist
CodePudding user response:
You can use ExpressibleByArrayLiteral, but don't. Your type is already available as SIMD2.
([0, 0] as SIMD2).scalarCount // 2