Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Array of UnicodeScalar into String in Swift

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"
like image 535
nacho4d Avatar asked Jul 25 '17 05:07

nacho4d


3 Answers

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"
like image 191
Leo Dabus Avatar answered Oct 09 '22 20:10

Leo Dabus


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)
like image 33
Martin R Avatar answered Oct 09 '22 22:10

Martin R


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
like image 33
OOPer Avatar answered Oct 09 '22 20:10

OOPer