如何在Swift 2.0中将clusted数组的元素添加到单个数组中?

时间:2015-09-19 01:19:40

标签: ios arrays swift2

我有以下数组:

var array1 = [[aruna,bala,chitra], [marya,navya,ovya], [jaya,kala,latha], [stella,taruna,unna]]
var array2 = []

如何将array1值的元素作为元素而不是数组添加和删除到array2。 像这样:

如果我想添加2 and 4数组,

array2 = [marya,navya,ovya,stella,taruna,unna]  //Expected Output

如果我想删除2数组

array2 = [stella,taruna,unna] //Expected Output

我无法像append一样使用array2.append(array1[[1]])来添加2个数组,因为错误说明了:

Cannot subscript a value of type [NSArray] with the index of type [int]这是完全正确的。

1 个答案:

答案 0 :(得分:1)

让我们假设这些都是Ints。为简单起见,我将使用实际的数字文字:

var array1 = [[1,2,3], [4,5,6], [7,8,9], [10,11,12]]
var array2 = array1[1] + array1[3] // [4,5,6,10,11,12]

另一种方式:

var array1 = [[1,2,3], [4,5,6], [7,8,9], [10,11,12]]
var array2 = [Int]()
array2 += array1[1]
array2 += array1[3] // [4,5,6,10,11,12]

另一种方式:

var array1 = [[1,2,3], [4,5,6], [7,8,9], [10,11,12]]
var array2 = Array([array1[1], array1[3]].flatten()) // [4,5,6,10,11,12]

编辑好的,您已经更改了代码。但答案是一样的:

let aruna = "aruna"
let bala = "bala"
let chitra = "chitra"
let marya = "marya"
let navya = "navya"
let ovya = "ovya"
let jaya = "jaya"
let kala = "kala"
let latha = "latha"
let stella = "stella"
let taruna = "taruna"
let unna = "unna"

var array1 = [[aruna,bala,chitra], [marya,navya,ovya], [jaya,kala,latha], [stella,taruna,unna]]

var array2 = Array([array1[1], array1[3]].flatten())
// ["marya", "navya", "ovya", "stella", "taruna", "unna"]