Swift:从数组中过滤特定范围的元素

时间:2016-03-14 16:49:09

标签: arrays swift filter range

我有一个这样的数组:

let arr = ["one", "two", "three", "four", "five"]

现在我想创建一个基于第一个但只包含特定范围(如1到3)的新数组,结果是:

let arrFiltered = ["two", "three", "four"]

我知道有一个.filter方法,但我无法找到如何从数组中过滤掉一系列元素。

2 个答案:

答案 0 :(得分:2)

您可以将下标与范围一起使用,它会生成一个ArraySlice,您可以使用Array初始化程序将其转换回数组:

let arr = ["one", "two", "three", "four", "five"]

let result = Array(arr[1...3])  // ["two", "three", "four"]

答案 1 :(得分:1)

var listOfNumbers = [1,2,3,10,100] //数组数组

listOfNumbers[0] // 1
listOfNumbers[1] // 2
listOfNumbers[2] // 3
listOfNumbers[3] // 10
listOfNumbers[4] // 100
//listOfNumbers[5]// this gives an error uncomment this line to see it

listOfNumbers[1...2] // [2, 3] this is a subsequence of the original array