public class HangulDecomposer {
private static let hangulSet = CharacterSet(charactersIn: "가".unicodeScalars.first! ... "힣".unicodeScalars.first!)
private static let firstIndex = "가".unicodeScalars.first!.value
private static let lastIndex = "힣".unicodeScalars.first!.value
private static let chosungCaseCount = UInt32(jungsungSet.count * jongsungSet.count)
private static let jungsungCaseCount = UInt32(jongsungSet.count)
private static let chosungSet = [
"ㄱ","ㄲ","ㄴ","ㄷ","ㄸ","ㄹ","ㅁ","ㅂ","ㅃ","ㅅ",
"ㅆ","ㅇ","ㅈ","ㅉ","ㅊ","ㅋ","ㅌ","ㅍ","ㅎ"
]
private static let jungsungSet = [
"ㅏ", "ㅐ", "ㅑ", "ㅒ", "ㅓ", "ㅔ","ㅕ", "ㅖ", "ㅗ", "ㅘ",
"ㅙ", "ㅚ","ㅛ", "ㅜ", "ㅝ", "ㅞ", "ㅟ", "ㅠ", "ㅡ", "ㅢ",
"ㅣ"
]
private static let jongsungSet = [
"","ㄱ","ㄲ","ㄳ","ㄴ","ㄵ","ㄶ","ㄷ","ㄹ","ㄺ",
"ㄻ","ㄼ","ㄽ","ㄾ","ㄿ","ㅀ","ㅁ","ㅂ","ㅄ","ㅅ",
"ㅆ","ㅇ","ㅈ","ㅊ","ㅋ","ㅌ","ㅍ","ㅎ"
]
private static let doubleJongsungSet = [
"ㄳ":"ㄱㅅ","ㄵ":"ㄴㅈ","ㄶ":"ㄴㅎ","ㄺ":"ㄹㄱ","ㄻ":"ㄹㅁ",
"ㄼ":"ㄹㅂ","ㄽ":"ㄹㅅ","ㄾ":"ㄹㅌ","ㄿ":"ㄹㅍ","ㅀ":"ㄹㅎ",
"ㅄ":"ㅂㅅ"
]
static func get(from: String) -> String {
from.unicodeScalars.map { decompose(from: $0) ?? "" }.joined()
}
private static func decompose(from unicode: UnicodeScalar) -> String? {
if hangulSet.contains(unicode) {
let index = unicode.value - firstIndex
let chosung = chosungSet[Int(index / chosungCaseCount)]
let jungsong = jungsungSet[Int((index % chosungCaseCount) / jungsungCaseCount)]
var jongsung = jongsungSet[Int(index % jungsungCaseCount)]
if let doubleJongsung = doubleJongsungSet[jongsung] {
jongsung = doubleJongsung
}
return chosung + jungsong + jongsung
}
return String(unicode)
}
}