Created
August 12, 2019 18:04
-
-
Save mturilin/b587d70fbd836fef43e436579e5b6aaa to your computer and use it in GitHub Desktop.
Hypenation in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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