THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
Sometimes, We want to return to elements from an array as a subarray.
subarray
is a slice of an array.
There are multiple ways to do this.
Swift provides a range operator(a…b) that contains start and end values and provides this to an array to get a subarray.
the end value of the range operator is always less than equal to the array length
Here is a valid range operator example
import Foundation
let numbers = [1, 2, 3, 4, 5,6,7,8,9]
print(numbers) // [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(type(of: numbers)) // Array<Int>
var subArray = numbers[0..<3] // 1,2,3,4,5
print(subArray) // [1, 2, 3]
print(type(of: subArray)) // ArraySlice<Int>
if you provide invalid end range values, It throws Fatal error: Array index is out of range and the below code throw this error.
import Foundation
let numbers = [1, 2, 3, 4, 5,6,7,8,9]
var subArray = numbers[0..<20] // 1,2,3,4,5
prefix methods have different variations
import Foundation
let numbers = [1, 2, 3, 4, 5,6,7,8,9]
print(numbers) // [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(type(of: numbers)) // Array<Int>
let subArray = numbers.prefix(5) // ArraySlice
print(subArray) // [1, 2, 3, 4, 5]
print(type(of: subArray)) // ArraySlice<Int>
let result=Array(subArray)
print(result) // [1, 2, 3, 4, 5]
print(type(of: result))// Array<Int>
Array prefix(upTo) example:
import Foundation
let numbers = [1, 2, 3, 4, 5,6,7,8,9]
print(numbers) // [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(type(of: numbers)) // Array<Int>
let subArray = numbers.prefix(upTo:5) // ArraySlice
print(subArray) // [1, 2, 3, 4, 5]
print(type(of: subArray)) // ArraySlice<Int>
let result=Array(subArray)
print(result) // [1, 2, 3, 4, 5]
print(type(of: result))// Array<Int>
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Array<Int>
[1, 2, 3, 4, 5]
ArraySlice<Int>
[1, 2, 3, 4, 5]
Array<Int>
Array prefix(through) example:
import Foundation
let numbers = [1, 2, 3, 4, 5,6,7,8,9]
print(numbers) // [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(type(of: numbers)) // Array<Int>
let subArray = numbers.prefix(through:5) // ArraySlice
print(subArray) // [1, 2, 3, 4, 5,6]
print(type(of: subArray)) // ArraySlice<Int>
let result=Array(subArray)
print(result) // [1, 2, 3, 4, 5,6]
print(type(of: result))// Array<Int>
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Array<Int>
[1, 2, 3, 4, 5, 6]
ArraySlice<Int>
[1, 2, 3, 4, 5, 6]
Array<Int>
🧮 Tags
Recent posts
Julia examples - Variable Type Nim example - Convert String to/from the Int How to get length of an array and sequence in Nim? Nim environment variables - read, set, delete, exists, and iterate examples? How to convert from single character to/from string in Nim?Related posts