I have an array of unicode scalars (Type is [UnicodeScalar]
)
like:
let array = [UnicodeScalar("f")!, UnicodeScalar("o")!, UnicodeScalar("o")!]
or
let array2 = "bar".unicodeScalars
how can I convert efficiently these arrays into a strings again?
Expect:
let string1 = ?? // "foo"
let string2 = ?? // "bar"
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)
Another way to convert [UnicodeScalar]
to String
:
let array = [UnicodeScalar("f")!, UnicodeScalar("o")!, UnicodeScalar("o")!]
let string1 = String(array.map{Character($0)})
print(string1 == "foo") //->true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With