How do I convert wchar_t array to Swift String?

I have a C module with a unicode string like this:
Code Block
wchar_t * helloWorld = L"Hello World";

I have all the bridging header and all, Swift sees the C variable, no problem with that part. However, how do I get this converted to a String in Swift? I was trying to do something like this:
Code Block
let hw = String(cString: helloWorld, encoding: .unicode)

Swift came back with an ugly error:
Code Block
Cannot convert value of type 'UnsafeMutablePointer<wchar_t>?' (aka 'Optional<UnsafeMutablePointer<Int32>>') to expected argument type 'UnsafePointer<CChar>' (aka 'UnsafePointer<Int8>')

Any idea how it is done? I could not find anything useful on Google. Thanks.
Answered by OOPer in 624456022
wchar_t is a system dependent type in C, I assume it used under the default settings of Apple's platform, meaning 32-bit wide.
Under the assumption, an L-prefixed string literal is made of Unicode Code Points, 32-bit each.
Unfortunately, Swift.String does not have an initializer taking a pointer to wchar_t.

You may need to write something like this:
Code Block
let byteSize = wcslen(helloWorld) * MemoryLayout<wchar_t>.stride
let data = Data(bytes: helloWorld, count: byteSize)
let encoding: String.Encoding = (1.littleEndian == 1) ? .utf32LittleEndian : .utf32BigEndian
let str = String(data: data, encoding: encoding)!



Accepted Answer
wchar_t is a system dependent type in C, I assume it used under the default settings of Apple's platform, meaning 32-bit wide.
Under the assumption, an L-prefixed string literal is made of Unicode Code Points, 32-bit each.
Unfortunately, Swift.String does not have an initializer taking a pointer to wchar_t.

You may need to write something like this:
Code Block
let byteSize = wcslen(helloWorld) * MemoryLayout<wchar_t>.stride
let data = Data(bytes: helloWorld, count: byteSize)
let encoding: String.Encoding = (1.littleEndian == 1) ? .utf32LittleEndian : .utf32BigEndian
let str = String(data: data, encoding: encoding)!



Thanks @OOPer, it works. But good grief, why is it so complicated in Swift? :-)
Happy to hear that it works for your project.

why is it so complicated in Swift? 

In fact, Swift.String has some initializers work with UTF-8 bytes, UTF-16 code units and Unicode Scalars.
And they make similar conversions more simple.

You should better send a feedback to Apple, or join the discussion in the Evolution category of forums.swift.org.
Here's a thread for example:
Additional String Processing APIs
How do I convert wchar_t array to Swift String?
 
 
Q