SeaWarrior404 SeaWarrior404 - 1 month ago 4
Swift Question

How to add elements from one array(Array 1) to another array(Array 2) after checking for a specific condition in array 1?

In the below code I want to first check the array[b] for elements less than 100 and then add all those elements to another array called resultArray. As it stands, the elements less than 100 are getting printed to console but I want to add those elements to the resultArray. What is the best way to do this in Swift 3?

var value = 1
var resultArray: [Int]
var b = [23,34,67,2,89,76,874]
for var c in b {
if c < 100 {

print("Numbers less than 15 are \(c) ")
}
c += 1
}

Answer

Use a simple filter:

let b = [23,34,67,2,89,76,874]
let r = b.filter { $0 < 100 }
print(r)

This outputs:

[23, 34, 67, 2, 89, 76]

If you wanted to use the code you started with, you need to append c to resultArray and make a few other minor tweaks:

var resultArray: [Int] = []
let b = [23,34,67,2,89,76,874]
for c in b {
    if c < 100 {
        resultArray.append(c)
    }
}
print(resultArray)

Another option (thanks Martin R) would be:

var resultArray: [Int] = []
let b = [23,34,67,2,89,76,874]
for c in b where c < 100 {
    resultArray.append(c)
}
print(resultArray)