I currently have a 2D Array (from JSON Decoding) that is declared as
struct workoutList : Codable {
let intervals : [[Double]]
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
intervals = try values.decodeIfPresent([[Double]].self, forKey: .intervals)!
}
When I print out the intervals array, it is a 2D Array that looks like:
Intervals:[[0.0, 50.0], [10.2, 55.0], [10.0, 73.0]]
While I can access the individual values via the matrix eg: intervals[0][1] = 50.0, I think it's easier for my purposes to separate it into 2 diff arrays. (each value in an array set is [time, percentage]. Essentially I'm looking to achieve these results:
[time] = [0.0,10.2,10.0] [percentage] = [50.0, 55.0, 73.0]
I have looked at flatmap but this only results in the removal of the 2D array into 1 single array of the form
[0.0, 50.0, 10.2, 55.0, 10.0 73.0]
I tried to look for examples using map but don't believe it helps.
I finally did this but looks ugly:
let flattenedArray = tabbar.workoutIntervals.flatMap {$0}
print(flattenedArray) // [0.0, 50.0, 10.2, 55.0, 10.0, 73.0]
var timeArray = [Double]()
var wattArray = [Double]()
for x in 0...flattenedArray.count - 1 {
if x % 2 == 0{
timeArray.append(flattenedArray[x] )
} else {
wattArray.append(flattenedArray[x] )
}
}
print("time:\(timeArray)") // [ 0.0, 10.2, 10.0]
print("watt:\(wattArray)") // [50.0, 55.0, 73.0]
Thanks
Rather than splitting into 2 arrays you can combine the data in a struct and use map
to convert the array
let intervals = [[0.0, 50.0], [10.2, 55.0], [10.0, 73.0]]
struct Interval {
let time: Double
let watt: Double
}
let workouts = intervals.map { Interval(time: $0[0], watt: $0[1])}
If you still want them in two arrays I think the easiest is to use forEach
var times = [Double]()
var watts = [Double]()
intervals.forEach {
times.append($0[0])
watts.append($0[1])
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.