仅从NSArray输出中获取字符串值

时间:2016-09-14 10:58:15

标签: arrays swift

我正在存储来自Json响应的值,如

self.NameArray = self.attachmentsArray.valueForKey("filename") as! NSArray 

输出:

NameArray(("Din.pdf","img.jpeg"),(),(),("41_58"))

我得到了这个输出。我需要让数组只有("Din.pdf","img.jpeg","41_58")

如何使用swift代码获取它?

1 个答案:

答案 0 :(得分:1)

  • NSArray转换为Swift类型[[String]]

    let NameArray:NSArray = [["Din.pdf","img.jpeg"], [], [], [ "41_58" ]]
    
    let swiftArray = NameArray as! [[String]]
    
    let flattenedArray = swiftArray.flatMap{ $0 }
    

致谢:Eric AyaFlatten a Array of Arrays in Swift

  • 如果您不想将其转换为Swift Type:

    let NameArray:NSArray = [["Din.pdf","img.jpeg"], [], [], [ "41_58" ]]
    
    let arrFiltered:NSMutableArray! = []
    
    for arr in NameArray {
        for a in arr as! NSArray {
            arrFiltered.addObject(a)
        }
    }
    
    print(arrFiltered)