Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Append every second item to Array

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"]
like image 871
user3110353 Avatar asked Jul 22 '15 05:07

user3110353


1 Answers

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]

like image 148
Ashish Kakkad Avatar answered Nov 11 '22 00:11

Ashish Kakkad