> func utf16ArrayToString (chars: [unichar]) -> String {
> var string = ""
> for char in chars { string.append(Character(UnicodeScalar(char))) }
> return string
> }
>
> Have any of you found any easier way to convert a unichar value or arrays of unichar values to Swift Strings?
The simplest way I’ve found that the type checker seems to guarantee will work is to (lazily) convert the array to UnicodeScalars, construct a UnicodeScalarView, and then build a string from it:
func utf16ArrayToString (chars: [unichar]) -> String {
let scalars = chars.lazy.map(UnicodeScalar.init)
let scalarView = String.UnicodeScalarView() + scalars
return String(scalarView)
}
// one-liner style
func utf16ArrayToString (chars: [unichar]) -> String {
return String(String.UnicodeScalarView() + chars.lazy.map(UnicodeScalar.init))
}
> I also find it very aggravating that I don’t have any good way to compare a literally represented Unicode character to a specific UTF16 value using the good ‘ole single quoted character approach of C and Obj-C and most other languages. I now create unichar constants for key characters, e.g.,
>
> let HyphenCharacter: unichar = 45 // '-'
>
>
> Would it be difficult to add to Swift the single quote delimiter to mean the UTF16 or UTF32 value of a character, as in ‘3’ or ‘V’ or ‘\n’ and so on?
You can actually add something like this to Swift yourself. unichar is just an alias for UInt16, so you can make UInt16 support character literals by making it conform to the UnicodeScalarLiteralConvertible protocol:
extension UInt16: UnicodeScalarLiteralConvertible {
public init(unicodeScalarLiteral value: UnicodeScalar) {
self.init(value.value)
}
}
Now anywhere you were previously able to write a UInt16/unichar, you can instead write a single-character string literal.
utf16ArrayToString(["a", "b", "c", "d", "e"])
--
Brent Royal-Gordon
Architechies