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
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])
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.
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]
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"]