3

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
}

}

1 Answer 1

3

As far as I tried on the IBM Swift Sandbox, CFStringTransform does not work on arbitrary CFMutableStrings. 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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot. It goes well, but it seems to make my website garbled. I am not sure whether UTF16 makes it garbled. What's your opinion?
@skyrealman, as you see, just a single function does not work as expected in a certain condition in Swift on Linux. Every single code may be the cause of your issue. Without a testable code shown, I cannot say any more.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.