0

I have a function that gathers all of the .jpg files in the Documents directory and all folders within it. The function then puts the file paths of the .jpgs into an array. What I need to do is filter a file defaultImage.jpg from the array. The problem I'm having is that the items in the array are paths to the jpg images so they are not strings. How can I filter either "theArray" or "files" or "theImagePaths" variables to remove the defaultImage.jpg? I've tried getting the index of defaultImage.jpg but again because the variables contain paths to the image files that doesn't seem to work.

I've tried - theArray.removeAll(where: {$0 == "defaultImage.jpg"}) but I couldn't get it to remove the image file.

static func buildPresentationArray() -> [String]
{
    let theDirectoryPath = ModelData.getDocumentsDirectory()
    let fm = FileManager.default
    var theArray = [String]()

    theArray.removeAll()

    let files = fm.enumerator(at: theDirectoryPath, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles])
    let theImagePaths = files!.filter{ ($0 as AnyObject).pathExtension == "jpg"}

    for theImagePath in theImagePaths
    {
        theArray.append((theImagePath as AnyObject).path)
    }

    return theArray
}

3 Answers 3

1

You can use a combination of filter(_:) and contains(_:) to get that working, i.e.

let filteredArray = theArray.filter({ !$0.contains("defaultImage.jpg") })
Sign up to request clarification or add additional context in comments.

Comments

1

Try this :

theArray.removeAll { (image: String) -> Bool in
    return image.contains("defaultImage.jpg")
}

Comments

0

From the URL get the last component and compare it with defaultImage.jpg

theArray = [URL]() 
theArray.removeAll(where: {$0.lastPathComponent == "defaultImage.jpg"})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.