在SWIFT中遍历数组计数偶数,打印计数和偶数

时间:2019-02-08 16:26:13

标签: arrays swift

import UIKit


var myArray = [1,2,3,4,5,6,7,8,9,10];
for myInt: Int in myArray{
//counts numbers in array
for i in 0..<myArray.count{
    //to find even number
    if myInt % 2 == 0 {


        print("Record Number \(i): \(myInt)")
}}}

它打印出每个偶数10次,而我只需要打印偶数。

1 个答案:

答案 0 :(得分:1)

您的目标是计算符合条件的元素数量(如果情况是偶数(number % 2 == 0),则需要打印该元素。

要实现此目的,请首先获取匹配条件的这些元素的编号,然后打印此编号。

为简单起见,我会在每个循环中保留您的内容

var matching = 0

for myInt in myArray {

    if myInt % 2 == 0 {
        matching += 1 // if number matching condition, increase count of matching elements
    }

}

print(number)

无论如何,使用计数过滤项(计数已过滤的元素数)可以使操作变得更加容易

let matching = myArray.filter({ $0 % 2 == 0 }).count

或者您可以使用reduce,每当该元素匹配条件增加初始值

let matching = myArray.reduce(0) { $1 % 2 == 0 ? $0 + 1 : $0 }

未来:在Swift 5中,您可以使用新引入的方法count(where:)来计算符合条件的元素的数量

let matching = myArray.count(where: { $0 % 2 == 0 })
相关问题