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
Array to ArraySliceWhen 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
You can learn more about ArraySlice with ArraySlice Structure Reference.
ArraySlice to ArrayOn 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: 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 to ArrayBecause 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 from your ArraySlice: you can get an Array (or any other array type that would make sense) from your ArraySlice.
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"]