#1. Using Array
subscript with range
With Swift 5, when you write…
let newNumbers = numbers[0...position]
… newNumbers
is not of type Array<Int>
but is of type ArraySlice<Int>
. That's because Array
's subscript(_:)
returns an ArraySlice<Element>
that, according to Apple, presents a view onto the storage of some larger array.
Besides, Swift also provides Array
an initializer called init(_:)
that allows us to create a new array from a sequence
(including ArraySlice
).
Therefore, you can use subscript(_:)
with init(_:)
in order to get a new array from the first n elements of an array:
let array = Array(10...14) // [10, 11, 12, 13, 14]
let arraySlice = array[0..<3] // using Range
//let arraySlice = array[0...2] // using ClosedRange also works
//let arraySlice = array[..<3] // using PartialRangeUpTo also works
//let arraySlice = array[...2] // using PartialRangeThrough also works
let newArray = Array(arraySlice)
print(newArray) // prints [10, 11, 12]
#2. Using Array
's prefix(_:)
method
Swift provides a prefix(_:)
method for types that conform to Collection
protocol (including Array
). prefix(_:)
has the following declaration:
func prefix(_ maxLength: Int) -> ArraySlice<Element>
Returns a subsequence, up to maxLength in length, containing the initial elements.
Apple also states:
If the maximum length exceeds the number of elements in the collection, the result contains all the elements in the collection.
Therefore, as an alternative to the previous example, you can use the following code in order to create a new array from the first elements of another array:
let array = Array(10...14) // [10, 11, 12, 13, 14]
let arraySlice = array.prefix(3)
let newArray = Array(arraySlice)
print(newArray) // prints [10, 11, 12]