Retrieving a fixed amount of data from a Swift Array

前端 未结 2 1073
情歌与酒
情歌与酒 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:00

    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])
    
    0 讨论(0)
  • 2021-01-22 23:04

    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"]
    
    0 讨论(0)
提交回复
热议问题