我有以下数组:
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]
这是完全正确的。
答案 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"]