2016-01-25 116 views
2

我從解析中檢索多個數組並將它們存儲在一個數組中。它目前正在工作,但是當我應用文本[indexpath.row]時,標籤是["cat", "dog"],而不是我想要cat, dog如何刪除數組數組中的[「」]?

var animal: [[String]] = [] 
    if let displayIntake = object["Animal"] as? [String]{ 

        self.animal.append(displayIntake) 
        print(self.animal) 
        //prints ["cat", "dog"] 
       } 

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 
    let cell: TutorBoxCell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! BoxCell 
    cell.info.text = "\(animal[indexPath.item])" 
    //info is a UILabel 
    //on the app the label appears ["cat", "dog"] instead I need it to be cat, dog 

回答

3

您可以在陣列上使用joinWithSeparator

它會將數組元素作爲一個String連接起來,用作爲參數傳遞的String分隔開來。

例子:

yourArray.joinWithSeparator(", ") 

貓,狗

使用這一個,如果它是一個數組的數組:

yourArray.map { $0.joinWithSeparator(", ") }.joinWithSeparator("") 

這一個手段,我們加入eac h子數組與「,」然後我們加入一個字符串的一切。

並給予你對我的意見數組的內容,適合你的組合將是這樣的例子:

let animals = [ ["dog", "cat"], ["chicken", "bat"] ] 

let results = animals.map { $0.joinWithSeparator(", ") } 

for content in results { 
    print(content) 
} 

打印

狗,貓
雞,蝙蝠

而只是爲了完整的例子:

let all = results.joinWithSeparator(" - ") 

print(all) 

打印

狗,貓 - 雞,蝙蝠

+0

我得到的錯誤'無法與類型的String' – stackerleet

+0

此錯誤的參數列表調用「與分離器加入」消息的裝置您正在將'joinWithSeparator'應用於一個字符串,而不是將其應用於數組。 – Moritz

+0

雖然動物被實例化爲一個數組。 – stackerleet