0

I have this array:

let numbers = [0,1,2,3,4,5,6,7,8,9]

And I want to append all numbers below 6 in this array below:

var belowSix = [Int]()

Here is what I have done and it works:

for number in numbers {
    if number < 6 {
        belowSix.append(number)
    }
}

Question:
It feels like this can be done in a smoother way, any suggestions?

4
  • Is the array always sorted? Commented May 31, 2017 at 12:00
  • @EricAya, yes it is Commented May 31, 2017 at 12:02
  • @SameSome What if your number array is [0,1,2,3,4,2,5,6,7,8,9] in this case it will not show 5 in your belowSix array if you use prefix(6) so better if you use filter not the prefix because prefix is used to get specific objects from array starting Commented May 31, 2017 at 12:11
  • @SameSome Have you tried prefix(6) with array [0,1,2,3,4,2,5,6,7,8,9], You will not get your desired result Commented May 31, 2017 at 13:03

2 Answers 2

3

Yes, You can use filter for that.

let belowSix = numbers.filter { $0 < 6 }
Sign up to request clarification or add additional context in comments.

Comments

0

If you want (up to) first 6 elements:

var belowSix = numbers.prefix(6)

If you want to get all elements below 6 use:

let belowSix = numbers.filter { $0 < 6 }

5 Comments

If the array is not sorted (and if does not contain all numbers), then prefix(6) won't work.
As OP wrote it always is.
Try this on an array with duplicates, even if it is sorted - say, [1,1,2,2,2,3,4,4,5,5,5,5,5]
Also what if array is having less object than 6 like [2,5,6,7,8]
@NiravD, then it will show all the values if it´s below.

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.