With Swift 5, according to your needs, you can choose one of the following 6 playground codes to solve your problem.
# 1. Using subscript(_:) index
let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"] let arraySlice = array[..<5] //let arraySlice = array[0..<5] // also works //let arraySlice = array[0...4] // also works //let arraySlice = array[...4] // also works let newArray = Array(arraySlice) print(newArray) // prints: ["A", "B", "C", "D", "E"]
# 2. Using the prefix(_:) method
Difficulty: O (1) if the collection matches RandomAccessCollection ; otherwise, O (k), where k is the number of elements to select at the beginning of the collection.
let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"] let arraySlice = array.prefix(5) let newArray = Array(arraySlice) print(newArray) // prints: ["A", "B", "C", "D", "E"]
Apple claims for prefix(_:) :
If the maximum length exceeds the number of elements in the collection, the result contains all the elements in the collection.
# 3. Using prefix(upTo:) method prefix(upTo:)
Difficulty: O (1)
let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"] let arraySlice = array.prefix(upTo: 5) let newArray = Array(arraySlice) print(newArray) // prints: ["A", "B", "C", "D", "E"]
Apple claims for prefix(upTo:) :
Using the prefix(upTo:) method is equivalent to using a partially half-open range as the collection index. prefix(upTo:) index is preferable to prefix(upTo:) .
# 4. Using prefix(through:) method prefix(through:)
let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"] let arraySlice = array.prefix(through: 4) let newArray = Array(arraySlice) print(newArray) // prints: ["A", "B", "C", "D", "E"]
# 5. Using removeSubrange(_:)
Difficulty: O (n), where n is the length of the collection.
var array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"] array.removeSubrange(5...) print(array)
# 6. Using dropLast(_:)
Difficulty: O (1) if the collection matches RandomAccessCollection ; otherwise, O (k), where k is the number of elements to delete.
let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"] let distance = array.distance(from: 5, to: array.endIndex) let arraySlice = array.dropLast(distance) let newArray = Array(arraySlice) print(newArray) // prints: ["A", "B", "C", "D", "E"]