John Smith John Smith - 27 days ago 6
iOS Question

Use pathExtension from Array as TableViewCell Image Source

I am displaying the Documents folder in a table view and now I want to make the picture the symbol of the suffix.

For example, if the name is "test.pdf", I want to display the pdf.png from the assets.

arrayDocuments = ["0.pdf", "1.pdf", "2.png", "3.jpg", "4.zip"]


I tried to use
= UIImage(named: arrayDocuments[indexPath.row])
and
= UIImage(named: (arrayDocuments[indexPath.row] as NSString).pathExtension)
but
.pathExtension
only allows NSString so I tried to convert the Array to NSArray as shown below but it didn't work either.

let nsa = NSArray(array: arrayDocuments)
if arrayDocuments[indexPath.row].hasSuffix("") {
} else {
cell.mySymbol.image = UIImage(named: (nsa[indexPath.row] as! NSString).pathExtension)
}

Answer Source

You do not need to convert the array to an NSArray.

You can cast your String to NSString if you wish to call pathExtension.

let filename = arrayDocuments[indexPath.row]
let ext = (filename as NSString).pathExtension
if ext.isEmpty {
    cell.mySymbol.image = nil
} else {
    cell.mySymbol.image = UIImage(named: ext)
}