2015-09-19 77 views
-1

我有以下陣列:如何在Swift 2.0中將數組的元素添加到單個數組中?

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

我怎麼可以添加和刪除陣列1值的元素到數組2剛剛元素,而不是數組。 像這樣:

,如果我想要添加2 and 4陣列,

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

,如果我想刪除2陣列

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

我不能使用appendarray2.append(array1[[1]])增加2數組錯誤說:

Cannot subscript a value of type [NSArray] with the index of type [int]這是完整的沒錯。

回答

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"] 
+0

因爲所有都是'字符串'我試過:'array2 = [array1 [1],array1 [3]]。flatten()as! [字符串]'但它沒有日誌崩潰 – AAA

+0

你能顯示你的真實代碼嗎?光禿禿的'a'不是一個字符串;這是一個變量名稱。顯示'a'和'b'和'c'等等如何得到值。 – matt

+0

另外,當您測試我的代碼時,請測試_my_代碼,而不是其他代碼。你根本沒有複製我給出的任何例子。你不能在Swift中說出你喜歡的任何東西。我沒有說任何東西,我把所有的東西都包裝在一個'Array(...)'中。這些事情是有原因的。 – matt

相關問題