Dinesh Kumar Dinesh Kumar - 2 months ago 8
Swift Question

Get only the string value from NSArray output

I am storing values from Json response like

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


Output:

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


I got this output. I need to get the array only having
("Din.pdf","img.jpeg","41_58")
.

How to get it using swift code?

Answer
  • Convert NSArray to Swift Type [[String]]:

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

Credits: Eric Aya and Flatten a Array of Arrays in Swift

  • If you do not want to convert it into 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)
    
Comments