3

i have a small problem.

I have an array with a integer of value:

let array = [99, 42, 34, 19, 167, 30, 49, 39, 75, 175, 270, 540]

How do I get all the values between 19 and 167 for example? There has to be a better way than a for iteration through all the integer value ? this is on swift. so i am looking for answer on swift. thanks in advance

3 Answers 3

4

In Swift, you can still do this using filter

let array = [99, 42, 34, 19, 167, 30, 49, 39, 75, 175, 270, 540]
let newArray = array.filter{$0 > 19 && $0 < 167}
print(newArray)
Sign up to request clarification or add additional context in comments.

1 Comment

Function that takes n as the parameter. In this case, .filter() runs through each array element and sets it as the value of n. The function then checks if the value of n passes the condition which is greater than 19 and less than 167. If it did not passed, the value will be removed from the array.
2

You can use filter and the pattern matching operator ~= which is able to filter a range.

let array = [99, 42, 34, 19, 167, 30, 49, 39, 75, 175, 270, 540]
let range = 19...167
let filteredArray = array.filter{ range ~= $0 }

Consider that this operator does not filter the edges 19 and 167. The result is

// [99, 42, 34, 19, 167, 30, 49, 39, 75]

To exclude the edges write 20...168 or 20..<167, then the result is

// [99, 42, 34, 30, 49, 39, 75]

Comments

0
let filtered = array.filter { (20..<167).contains($0) }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.