John Smith John Smith - 6 months ago 39
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", ""]

I tried to use
= UIImage(named: arrayDocuments[indexPath.row])
= UIImage(named: (arrayDocuments[indexPath.row] as NSString).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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download