Reputation: 522
I have a swift array "Monthdata" that I want to append every second value in my months array.
var monthData = []
let months = ["Jul 12","Aug 12","Sep 12","Oct 12"]
for month in months {
self.monthData.append(month)
}
So basically I the monthData array to look like:
["Aug 12","Oct 12"]
Upvotes: 6
Views: 4578
Reputation: 5076
To solve this, you can use a Strides class and a map
method:
let months = ["Jul 12","Aug 12","Sep 12","Oct 12"]
let monthData = stride(from: 1, to: months.count, by: 2).map { (value:Int) -> String in
return months[value]
}
print(monthData)
Upvotes: 0
Reputation: 7168
Swift 3 (based on @maxkonovalov's answer)
let array = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
let step = 2
let filtered = array.enumerated().flatMap { $0.offset % step == 0 ? $0.element : nil }
// filtered: ["0", "2", "4", "6", "8"]
Upvotes: 2
Reputation: 3719
There's a more compact version to filter an array by element's index.
An example of how to find every Nth element in an array (swift 2.0):
let array = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
let n = 2
let filteredArray = array.enumerate().flatMap { $0.index % n == 0 ? $0.element : nil }
// filteredArray = ["0", "2", "4", "6", "8"]
Upvotes: 0
Reputation: 3905
You can also use the swift array filter
method to get the filtered array,
monthData = months.filter{ (dataValue) in (find(months, dataValue)! % 2 != 0) }
Upvotes: 3
Reputation: 23882
Try to use modulo operator ( % )
var monthData = Array<String>()
let months = ["Jul 12","Aug 12","Sep 12","Oct 12"]
var i : Int = 1
for month in months{
if(i%2 == 0){
monthData.append(month)
}
i = i + 1
}
println(monthData)
Output :
[Aug 12, Oct 12]
Upvotes: 6