Reputation: 33
I want to cast some Latin strings to English(PinYin) with swift on Linux,so I wrote a function, but it seems to have some errors in it. It can run in xcode on mac os, but it will go wrong on Linux. I think there are something wrong in the conversion between CFString and string. I don't know what it is. Can someone help me? Thanks
import Foundation
#if os(Linux)
import CoreFoundation
import Glibc
#endif
public extension String{
func transformToLatinStripDiacritics() -> String{
let nsStr = NSMutableString(string: self)
let str = unsafeBitCast(nsStr, to: CFMutableString.self)
if CFStringTransform(str, nil, kCFStringTransformToLatin, false){
if CFStringTransform(str, nil, kCFStringTransformStripDiacritics, false){
let s = String(describing: unsafeBitCast(str, to: NSMutableString.self) as NSString)
return s
}
return self
}
return self
}
}
Upvotes: 3
Views: 717
Reputation: 47876
As far as I tried on the IBM Swift Sandbox, CFStringTransform
does not work on arbitrary CFMutableString
s. Seems it requires CFMutableString
based on UTF-16 representation.
import Foundation
#if os(Linux)
import CoreFoundation
import Glibc
#endif
public extension String {
func transformToLatinStripDiacritics() -> String{
let chars = Array(self.utf16)
let cfStr = CFStringCreateWithCharacters(nil, chars, self.utf16.count)
let str = CFStringCreateMutableCopy(nil, 0, cfStr)!
if CFStringTransform(str, nil, kCFStringTransformToLatin, false) {
if CFStringTransform(str, nil, kCFStringTransformStripDiacritics, false) {
return String(describing: str)
}
return self
}
return self
}
}
print("我在大阪住".transformToLatinStripDiacritics()) //->wo zai da ban zhu
Tested only for a few examples. So, this may not be the best solution for your issue.
Upvotes: 3