Convert Array of UnicodeScalar into String in Swift
You can use this extension from @dfri to initialize a string from a UnicodeScalar sequence as follow:
extension Sequence where Element == UnicodeScalar {
var string: String { .init(String.UnicodeScalarView(self)) }
}
let array: [UnicodeScalar] = ["f", "o", "o"]
print(array.string) // "foo\n"
The second case is simpler because array2
is a UnicodeScalarView
and not an array:
let array2 = "bar".unicodeScalars
let str2 = String(array2)
print(str2) // bar
If you have an array (or any sequence) of Unicode scalars then you can start with an empty string
and append the elements to its unicodeScalars
view:
let array = [UnicodeScalar("f")!, UnicodeScalar("o")!, UnicodeScalar("o")!]
// Or: let array: [UnicodeScalar] = ["f", "o", "o"]
var str1 = ""
str1.unicodeScalars.append(contentsOf: array)
print(str1) // foo
Of course you can define a custom extension for that purpose:
extension String {
init<S: Sequence>(unicodeScalars ucs: S)
where S.Iterator.Element == UnicodeScalar
{
var s = ""
s.unicodeScalars.append(contentsOf: ucs)
self = s
}
}
let str1 = String(unicodeScalars: array)