Skip to content

Instantly share code, notes, and snippets.

@regexident
Forked from frankrausch/String+Hyphenation.swift
Created September 27, 2017 09:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save regexident/1baf9af8b9ee0040bcc65c06827be661 to your computer and use it in GitHub Desktop.
Save regexident/1baf9af8b9ee0040bcc65c06827be661 to your computer and use it in GitHub Desktop.
Returns a String with soft hyphens (U+00AD)
import Foundation
extension String {
func hyphenated(languageCode: String) -> String {
let locale = Locale(identifier: languageCode)
return self.hyphenated(locale: locale)
}
func hyphenated(locale: Locale) -> String {
guard CFStringIsHyphenationAvailableForLocale(locale as CFLocale) else { return self }
var s = self
let fullRange = CFRangeMake(0, s.utf16.count)
var hyphenationLocations = [CFIndex]()
for (i, _) in s.utf16.enumerated() {
let location: CFIndex = CFStringGetHyphenationLocationBeforeIndex(s as CFString, i, fullRange, 0, locale as CFLocale, nil)
if !hyphenationLocations.contains(location) {
hyphenationLocations.append(location)
}
}
for l in hyphenationLocations.reversed() {
guard l > 0 else { continue }
let strIndex = String.UTF16View.Index(encodedOffset: l)
// insert soft hyphen:
s.insert("\u{00AD}", at: strIndex)
// or insert a regular hyphen to debug:
// s.insert("-", at: strIndex)
}
return s
}
}
// print("""
// Here’s to the crazy ones, the misfits, the rebels, the troublemakers, the round pegs in the square holes…the ones who see things differently—they’re not fond of rules…You can quote them, disagree with them, glorify or vilify them, but the only thing you can’t do is ignore them because they change things…they push the human race forward, and while some may see them as the crazy ones, we see genius, because the ones who are crazy enough to think that they can change the world, are the ones who do.
// """.hyphenated(languageCode: "en"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment