Home > Net >  How do i use joined() function after using sorted() in swift?
How do i use joined() function after using sorted() in swift?

Time:12-16

let var1 = "AnyCode".sorted()
print(var1.joined(separator:""))

ERROR: No exact matches in call to instance method 'joined'

I am trying to joined the array after sorting the string. = "AnyCode"

I was expecting the output was = ACdenoy

But it is giving an error.

CodePudding user response:

A Swift String is a collection of Characters, and sorted() applied to a collection returns an array with the collection elements in sorted order.

So var1 has the type [Character], and you can simply create a new string from that array with:

let var1 = "AnyCode".sorted()
print(String(var1)) // ACdenoy

CodePudding user response:

Alternatively to Martin R's answer (but not better than that answer), you might have said

print(var1.map(String.init).joined())

...turning the characters to strings before trying to join the array elements.

  • Related