Swift将每秒项添加到Array

时间:2015-07-22 05:37:51

标签: ios arrays swift append enumeration

我有一个快速阵列" Monthdata"我想在我的月份数组中附加每秒的值。

var monthData = []
let months = ["Jul 12","Aug 12","Sep 12","Oct 12"]

for month in months {
 self.monthData.append(month)
}

所以基本上我将monthData数组看起来像:

["Aug 12","Oct 12"]

5 个答案:

答案 0 :(得分:4)

尝试使用模运算符(%)

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)

输出

  

[8月12日,10月12日]

答案 1 :(得分:3)

您还可以使用swift数组filter方法获取已过滤的数组

monthData = months.filter{ (dataValue) in (find(months, dataValue)! % 2 != 0) }

答案 2 :(得分:2)

Swift 3 (基于@ maxkonovalov的答案)

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"]

答案 3 :(得分:0)

有一个更紧凑的版本可以按元素的索引过滤数组。

如何查找数组中的每个第N个元素的示例(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"]

答案 4 :(得分:0)

要解决此问题,您可以使用Strides类和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)