This works for me:

var test = [1, 2, 3]
var n = 2
var test2 = test[0..<n]

Your issue could be with how you're declaring your array to begin with.

EDIT:

To fix your function, you have to cast your Slice to an array:

func aFunction(numbers: Array<Int>, position: Int) -> Array<Int> {
    var newNumbers = Array(numbers[0..<position])
    return newNumbers
}

// test
aFunction([1, 2, 3], 2) // returns [1, 2]
Answer from Cezary Wojcik on Stack Overflow
🌐
Swift Forums
forums.swift.org › using swift
Is a range of Ints actually an array? - Using Swift - Swift Forums
March 1, 2023 - If I have a range of type Int, i.e., (2…100) is that range in fact an array of Ints?
🌐
Programiz
programiz.com › swift-programming › ranges
Ranges in Swift (With Examples)
let languages = ["Swift", "Java", "C"] // access array elements print(languages[0...2]) ... Here, the range 0...2 acts as array indices and helps us access all array elements.
Top answer
1 of 6
229

This works for me:

var test = [1, 2, 3]
var n = 2
var test2 = test[0..<n]

Your issue could be with how you're declaring your array to begin with.

EDIT:

To fix your function, you have to cast your Slice to an array:

func aFunction(numbers: Array<Int>, position: Int) -> Array<Int> {
    var newNumbers = Array(numbers[0..<position])
    return newNumbers
}

// test
aFunction([1, 2, 3], 2) // returns [1, 2]
2 of 6
152

#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]
🌐
DhiWise
dhiwise.com › post › swift-range-to-array-understanding-and-implementing-with-ease
Swift Range to Array Conversion: Ultimate Guide for Developers
September 5, 2024 - When converting a range to an array, it's important to ensure that the bounds correspond to valid array indexes. If the upper bound exceeds the array's count, you'll encounter a fatal error. Let's look at some examples to see Swift ranges in action.
🌐
Udacity
udacity.com › blog › 2023 › 05 › swift-ranges.html
Swift Ranges | Udacity
May 22, 2023 - Writing a Swift range is easy! We begin with the lower bound value, insert “…”, and end with an upper bound value. The “…” is an operator that includes the upper and lower limits of the range.
🌐
SwiftLee
avanderlee.com › swiftlee › swift › ranges in swift explained with code examples
Ranges in Swift explained with code examples - SwiftLee
May 15, 2023 - A half-open range defines a range ... its final value. Like with the closed range, the value of a must not be greater than b. The half-open operator can be used to iterate over zero-based lists such as arrays and collections in Swift in which you want to iterate up to but not ...
Top answer
1 of 3
9

With Swift 4, there is many ways to solve your problem. According to your needs, you may choose one of the six following patterns.


#1. Using Array dropFirst() method

let array = ["a", "b", "c"]
let arraySlice = array.dropFirst()
let newArray = Array(arraySlice)
print(newArray) // prints ["b", "c"]

#2. Using Array suffix(from:) method

let array = ["a", "b", "c"]
let arraySlice = array.suffix(from: 1)
let newArray = Array(arraySlice)
print(newArray) // prints ["b", "c"]

#3. Using Array suffix(_:) method

let array = ["a", "b", "c"]
let arraySlice = array.suffix(array.endIndex.advanced(by: -1))
// let arraySlice = array.suffix(array.count - 1) // also works
let newArray = Array(arraySlice)
print(newArray) // prints ["b", "c"]

#4. Using Array subscript(_:​) and CountableRange

let array = ["a", "b", "c"]
let range = array.startIndex.advanced(by: 1) ..< array.endIndex
// let range = 1 ..< array.count // also works
let arraySlice = array[range]
let newArray = Array(arraySlice)
print(newArray) // prints ["b", "c"]

#5. Using Array subscript(_:​) and CountableClosedRange

let array = ["a", "b", "c"]
let range = 1 ... array.count - 1 // also works
let arraySlice = array[range]
let newArray = Array(arraySlice)
print(newArray) // prints ["b", "c"]

#6. Using Array subscript(_:​) and CountablePartialRangeFrom

let array = ["a", "b", "c"]
let range = 1...
let arraySlice = array[range]
let newArray = Array(arraySlice)
print(newArray) // prints ["b", "c"]
2 of 3
5

You can get sub range of an swift array like that:

let array =[ "a", "b", "c"]
//be sure that your array.count has more than 1 item (in this case)
let subArray1 = array[1..<array.count]
print(subArray1)
//or
let subArray2 = array[1...array.count-1]
print(subArray2)

This is 2 notes from Swift Programming Language book

“Use .. to make a range that omits its upper value, and use ... to make a range that includes both values.”

And

“If you try to use subscript syntax to retrieve or set a value for an index that is outside of an array’s existing bounds, you will trigger a runtime error. However, you can check that an index is valid before using it, by comparing it to the array’s count property. Except when count is 0 (meaning the array is empty), the largest valid index in an array will always be count - 1, because arrays are indexed from zero.”

🌐
Dot Net Perls
dotnetperls.com › range-swift
Swift - Range Examples - Dot Net Perls
In Swift we can create ranges that do not include the second (end) number. These use a "less than" sign. These are called half-open ranges. Tip With this operator, we can get a range of all the indexes in an array without subtracting one from the array's count.
Find elsewhere
🌐
GitHub
gist.github.com › nubbel › d5a3639bea96ad568cf2
Swift: convert range to array · GitHub
import Foundation public extension Range where Bound: Strideable, Bound.Stride: SignedInteger { /// Convert to an array. func asArray() -> [Bound] { Array(self) } } public extension ClosedRange where Bound: Strideable, Bound.Stride: SignedInteger { /// Convert to an array.
🌐
Apple Developer
developer.apple.com › documentation › swift › range
Range | Apple Developer Documentation
A half-open interval from a lower bound up to, but not including, an upper bound.
🌐
TutorialsPoint
tutorialspoint.com › new-array-from-index-range-swift
New Array from Index Range Swift
In Swift, you can create an array using the ArraySlice type. The following examples will show how to use the ArraySlice type. You can create an extension as well to define the subscript method. In the following example, we create an array of numbers with values from 0 to 9 and then create a range of indices from startIndex to endIndex (exclusive).
🌐
Swdevnotes
swdevnotes.com › swift › 2023 › arrayslice-with-range-operator-and-prefix-in-swift
ArraySlice with range operator and Prefix in Swift | Software Development Notes
ArraySlice is used in Swift to return a view on a subset of a collection without the overhead of making a copy of the collection. The half-open range (..<) and closed range (...) operators are used to specify the index range to retrieve. An error will be thrown if the indices specified are out of range.
🌐
Medium
medium.com › mobile-app-development-publication › how-to-use-range-operators-in-swift-aadb8cf840ee
How to Use Range Operators in Swift | by Shashank Thakur | Mobile App Development Publication | Medium
September 2, 2023 - By mastering closed and half-open ranges, one-sided ranges, and the stride operator, you can write more concise and expressive Swift code. These operators not only enhance code readability but also improve performance by efficiently specifying the range of values you want to work with. So, whether you’re iterating through an array or performing calculations over a specific range of numbers, Swift’s range operators have got you covered.
🌐
Medium
medium.com › @bakshioye › range-in-swift-the-elemental-one-b2e599b8855b
Range in Swift: The elemental one | by Shubham Bakshi | Medium
May 13, 2024 - // Create an Array of first 10 elements var myArray = Array(1...10)// Creating a new array with first five elements of previous array let myModifiedArray = myArray[0…4] Not bad, Right ? There are 3 main categories for ranges — · Closed Ranges : ClosedRange and CountableClosedRange ·
🌐
Sarunw
sarunw.com › posts › how-to-get-first-n-elements-of-swift-array
How to get the first N elements of array in Swift | Sarunw
December 10, 2020 - Swift offers several range operators to work with the array subscript(_:). Let's say we want to retrieve the first three elements from an array.
🌐
DhiWise
dhiwise.com › post › streamlining-sequences-with-swift-range-operator
Simplifying Sequence Operations with Swift Range Operator
September 5, 2024 - Here, using a range allows you to print all the elements from the array index of the value 30 to the end of the array. Remember, using an incorrect index can throw a fatal error, so verifying the index before creating a range ensures safe execution ...
🌐
Make App Pie
makeapppie.com › 2019 › 03 › 20 › ranges-in-swift
Ranges in Swift – Make App Pie
March 20, 2019 - For a simple example, I’ll write a snippet of code to check if an index is in a given array. I’ll check for element 4 and get Ice cream. ... I’ve stuck to Integers here, but ranges can be other types as well. Four example, you can add a range of Double, then check if a valur exists inthat range quickly. One important caution I mentioned earlier: Unlike other Swift types, Range and NSRange is not the same thing.
🌐
Codecademy
codecademy.com › docs › swift › ranges
Swift | Ranges | Codecademy
November 27, 2023 - Ranges are used to create an interval of values. There are two kinds of range structures, Range for creating half-open ranges and ClosedRange for creating closed ranges. ... Learn how to build iOS applications with Swift and SwiftUI and publish ...