Retrieving a fixed amount of data from a Swift Array

前端 未结 2 1091
情歌与酒
情歌与酒 2021-01-22 22:33

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

2条回答
  •  春和景丽
    2021-01-22 23:04

    From Array to ArraySlice

    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
    

    You can learn more about ArraySlice with ArraySlice Structure Reference.


    From ArraySlice to Array

    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: 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 to Array

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

提交回复
热议问题