2016-01-25 63 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