从Array<Int> 到ArraySlice<Int>
下标Array时,返回对象的类型为ArraySlice:
let toPlotLines = [200, 300, 400, 500, 600, 322, 435] // type: [Int]
let arraySlice = toPlotLines[0 ..< 4] // type: ArraySlice<Int>
您可以通过ArraySlice Structure Reference了解更多关于ArraySlice的信息。
从ArraySlice<Int> 到Array<Int>
一方面,ArraySlice 符合从SequenceType 继承自身的CollectionType 协议。另一方面,Array 有一个初始化器 init(_:),其声明如下:
init<S : SequenceType where S.Generator.Element == _Buffer.Element>(_ s: S)
因此,可以轻松地从ArraySlice 获得新的Array:
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> 到Array<String>
因为ArraySlice符合SequenceType,所以可以在其上使用map(或其他函数方法,如filter和reduce)。因此,您不仅可以从ArraySlice<Int> 获得Array<Int>:您还可以从ArraySlice<Int> 获得Array<String>(或任何其他有意义的数组类型)。
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"]