简体   繁体   中英

Swift remove extended characters if string contains certain characters?

I know the title is convoluted but essentially im trying to do this

    let gif = UIImage(gifName: (String(format: "%03d", self.animal.speciesId!)))
    self.gifIBO.setGifImage(gif, manager: gifManager)
    gifIBO.contentMode = UIViewContentMode.center

Here is my code. I have a collection of images that I am grabbing from that are numbered using the format "%03d" ex: (001, 002, 010). However I have over 1000 images and some of these images contain extra letters.

ex: 300-f.gif, 231-m.gif

These images are skipped over. My current solution is to rename every image that has extended characters. Is there any native way for swift to remove these extended characters when it spots an image that fills certain requirements?

For example. If it finds image 300-f.gif but the first three characters match, it needs to remove the rest of the string and use that image instead of skipping over it and returning

Could not find 300.gif

on the console.

You can iterate over all gifs in your bundles and look for the one that starts with speciesId :

let gif = Bundle.main.urls(forResourcesWithExtension: "gif", subdirectory: nil)!
    .first {
        let pattern = String(format: "%03d(-.)?", speciesId)
        return $0.lastPathComponent.range(of: pattern, options: [.regularExpression]) != nil
    }.map {
        UIImage(contentsOfFile: $0.path)!
    }
  • Bundle.main.urls(...) lists all gif files within your main bundle
  • first searches for the first file whose name matches a certain condition. The condition is a regex pattern based on your speciesId . The pattern will work out to something like 001(-.)? which is the regex way of saying: "the string 001 , optionally followed by a dash ( - ) and another letter ( . means whatever letter)"
  • map turns the path into a UIImage for you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM