user3994005
user3994005

Reputation:

Retrieving a fixed amount of data from a Swift Array

I have var toPlotLines:[Int] = [200, 300, 400, 500, 600, 322, 435] and I want to retrieve the first four integers from the array. Can I do that without having to loop in Swift. I tried this graphView.graphPoints = toPlotLines[0..<n] where graphPoints is an empty integer array but, I keep getting this error:

Cannot subscript a value of type [int]

Upvotes: 2

Views: 183

Answers (2)

Imanou Petit
Imanou Petit

Reputation: 92599

From Array<Int> to ArraySlice<Int>

When you subscript to an Array, the type of the returned object is an ArraySlice:

let toPlotLines = [200, 300, 400, 500, 600, 322, 435] // type: [Int]
let arraySlice = toPlotLines[0 ..< 4] // type: ArraySlice<Int>

You can learn more about ArraySlice with ArraySlice Structure Reference.


From ArraySlice<Int> to Array<Int>

On one hand, ArraySlice conforms to CollectionType protocol that inherits itself from SequenceType. On the other hand, Array has an initializer init(_:) with the following declaration:

init<S : SequenceType where S.Generator.Element == _Buffer.Element>(_ s: S)

Therefore, it's possible to get a new Array from an ArraySlice easily:

let toPlotLines = [200, 300, 400, 500, 600, 322, 435]
let arraySlice = toPlotLines[0 ..< 4]
let newArray = Array(arraySlice)
print(newArray) // prints: [200, 300, 400, 500]

From ArraySlice<Int> to Array<String>

Because ArraySlice conforms to SequenceType, you can use map (or other functional methods like filter and reduce) on it. Thereby, you are not limited to get an Array<Int> from your ArraySlice<Int>: you can get an Array<String> (or any other array type that would make sense) from your ArraySlice<Int>.

let toPlotLines = [200, 300, 400, 500, 600, 322, 435]
let arraySlice = toPlotLines[0 ..< 4]
let stringArray = arraySlice.map { String($0) }
print(stringArray) // prints: ["200", "300", "400", "500"]

Upvotes: 1

Martin R
Martin R

Reputation: 540105

The error message is misleading. The problem is that toPlotLines[0 ..< n] is not an Array but an ArraySlice:

The Array-like type that represents a sub-sequence of any Array, ContiguousArray, or other ArraySlice.

To create a "real array", use

graphView.graphPoints = Array(toPlotLines[0 ..< n])

Upvotes: 5

Related Questions