Skip to content

Instantly share code, notes, and snippets.

@mturilin
Created August 12, 2019 18:04
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 mturilin/b587d70fbd836fef43e436579e5b6aaa to your computer and use it in GitHub Desktop.
Save mturilin/b587d70fbd836fef43e436579e5b6aaa to your computer and use it in GitHub Desktop.
Hypenation in Swift
import Foundation
extension String {
func hungarianHyphenated() -> String {
return hyphenated(locale: Locale(identifier: "hu_HU"))
}
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.indices.reversed() {
let location: CFIndex = CFStringGetHyphenationLocationBeforeIndex(s as CFString, i.utf16Offset(in: self), fullRange, 0, locale as CFLocale, nil)
if location < 0 {
return s
}
if hyphenationLocations.last != location {
hyphenationLocations.append(location)
let strIndex = String.Index(utf16Offset: location, in: s)
s.insert("\u{00AD}", at: strIndex)
}
}
return s
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment