In Swift, is there a clever way of using the higher order methods on Array to return the 5 first objects? The obj-c way of doing it was saving an index, and for-loop throug
The Prefix function is definitely the most efficient way of solving this problem, but you can also use for-in loops like the following:
let array = [1,2,3,4,5,6,7,8,9]
let maxNum = 5
var iterationNumber = 0
var firstNumbers = [Int()]
if array.count > maxNum{
for i in array{
iterationNumber += 1
if iterationNumber <= maxNum{
firstNumbers.append(i)
}
}
firstNumbers.remove(at: 0)
print(firstNumbers)
} else {
print("There were not \(maxNum) items in the array.")
}
This solution takes up many lines of code but checks to see if there are enough items in the array to carry out the program, then continues and solves the problem.
This solution uses many basic functions including array.count
, which returns the amount of items in the array, not the position of last item in the array. It also uses array.append
, which adds things onto the end of the array. Lastly, it uses array.remove
, which removes the array's item that has a specified position.
I have tested it it and it works for at least swift 5.