Home > Software engineering >  How does array subIndex works in swift?
How does array subIndex works in swift?

Time:11-01

let tools = ["a", "b", "c", "d"]
let index = 1
let target = "a"

let leftDirectionArray = Array(tools.reversed())
let leftDirection = leftDirectionArray[(tools.count - index) - 1 ..< tools.count]
print("leftDirectionArray: \(leftDirectionArray)")
print("leftDirection: \(leftDirection)")
print("leftDirection count: \(leftDirection.count)")

let firstIndexA = leftDirection.firstIndex { $0 == target } ?? 0
let firstIndexB = leftDirection.firstIndex(of: target) ?? 0

print("firstIndexA: \(firstIndexA)")
print("firstIndexB: \(firstIndexB)")

Outputs

leftDirectionArray: ["d", "c", "b", "a"]
leftDirection: ["b", "a"]
leftDirection count: 2
firstIndexA: 3
firstIndexB: 3

So my question is why is the return for firstIndex is 3 when there should be only 2 in the array? does it mean the firstIndex still does the operation on the original array?

CodePudding user response:

leftDirection is not an Array but an ArraySlice and this is described in the documentation as

an ArraySlice instance presents a view onto the storage of a larger array

So the elements you see are the elements of leftDirectionArray and their position in the real array

print(type(of: leftDirection))
leftDirection.indices.forEach { print($0) }

ArraySlice
2
3

  • Related