Swift version: 5.6
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.
SPONSORED Let’s face it, SwiftUI previews are limited, slow, and painful. Judo takes a different approach to building visually—think Interface Builder for SwiftUI. Build your interface in a completely visual canvas, then drag and drop into your Xcode project and wire up button clicks to custom code. Download the Mac App and start your free trial today!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Available from iOS 8.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.