UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Day 23, Milestone Project 1-3: Strip the ".png" off of filenames & Trim "@2x" or "@3x" off of them too?

Forums > 100 Days of Swift

I'd love to know if there's a Swift method to split the file name from its extension. For example: from estonia.png into estonia + png?

Also, how did everyone remove the 2x, 3x filename thingy so that the country name is displayed properly? I was thinking of creating an enum to return each proper country name to be shown as cell.textLabel?.text in ViewController.swift and title in DetailViewController.swift. But this seems to be overwhelming and not efficient, as the enum would have to be updated manually when a new flag image is added.

Thank you in advance!

3      

I found some solutions to my issues. Would like to share here if any folk encounters the same thing

  1. To split the country name from its extension, add this code to either ViewController.swift or DetailViewController.swift, not both, and preferrably at the end of the file, just below the scope of the view controller
extension String {
  func getFileName() -> String {
    return URL(fileURLWithPath: self).deletingPathExtension().lastPathComponent
  }

  func getFileExtension() -> String {
    return URL(fileURLWithPath: self).pathExtension
  }
}

Then call getFileName() on those strings that I'd like to strip off of the extension part. For instance, to display properly capitalized country name in the main controller's table cell

cell.textLabel?.text = flagNames[indexPath.row].getFileName().capitalized
  1. To get rid of the suffix @2x or @3x, there's a built-in method to strip off the last x characters of a string. It's .dropLast(). It's syntax is something like this:
    let str = "Hello"
    str.dropLast(_ k: Int)
    // This however, returns a Substring
    // So then use String() to convert into a String
    // Read more here https://www.hackingwithswift.com/example-code/language/how-to-convert-a-substring-to-a-string

Therefore, my issue seems to be solved. But instead of .uppercased() the trimmed filename, I'd prefer changing the filename into full name, eg. united kingdom@3x.png instead of uk@3x.png, and use .capitalized instead.

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.