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

How to convert a string to a safe format for URL slugs and filenames

Swift version: 5.6

Paul Hudson    @twostraws   

Swift strings are extraordinarily complex beasts, allowing you to mix in characters from any language – including emoji – freely. While this is really important to display text, it can also cause havoc while trying to create URLs and filenames, so if you need to refer to a string in those places you should first convert it to a slug.

If you look at a URL like https://www.hackingwithswift.com/whats-new-in-ios-11, the slug is the last part – “whats-new-in-ios-11”. The conversion process stripped out punctuation (the apostrophe in “What’s”, lowercased it all, removed any non-Latin characters, then used dashed for word separators rather than spaces.

This takes a little more work to do than you might think, particularly because of the way you need to convert non-Latin and accented characters. For example, “ä” needs to be converted to “a”, and languages such as German convert “ß” into “ss” when they are rendered as Latin characters.

If you want to get the best conversion possible, you need to use Foundation’s StringTransform type then call applyingTransform() on your string. You can then split by any characters that can’t be used in slugs, and re-join on “-” to get your finished URL.

Rather than try to write all that yourself, here’s an easy extension you can drop in:

extension String {
    private static let slugSafeCharacters = CharacterSet(charactersIn: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-")

    public func convertedToSlug() -> String? {
        if let latin = self.applyingTransform(StringTransform("Any-Latin; Latin-ASCII; Lower;"), reverse: false) {
            let urlComponents = latin.components(separatedBy: String.slugSafeCharacters.inverted)
            let result = urlComponents.filter { $0 != "" }.joined(separator: "-")

            if result.count > 0 {
                return result
            }
        }

        return nil
    }
}

If you use Swift’s package manager, you can find that wrapped up in a cross-platform library in my SwiftSlug project. It’s available on GitHub at http://github.com/twostraws/SwiftSlug.

Hacking with Swift is sponsored by Proxyman

SPONSORED Proxyman: A high-performance, native macOS app for developers to easily capture, inspect, and manipulate HTTP/HTTPS traffic. The ultimate tool for debugging network traffic, supporting both iOS and Android simulators and physical devices.

Start for free

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

Available from iOS 8.0

Similar solutions…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 3.5/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.