Search code examples
swiftsplitswift-playground

Strange behavior with split(separator: )


Why this line of code works in Xcode playground but not in actual Xcode project?

let first = string.split(separator: "").sorted().joined()

Error:

Cannot convert value of type 'String' to expected argument type 'String.Element' (aka 'Character')

I want to convert string to array of characters. split(separator: "") solves the problem but for some reason the code works only in my playground. The Swift version is 5.7 in both the project and the playground.


Solution

  • I don't know why you're seeing this discrepancy between playgrounds and regular code, but there's a workaround that sidesteps it entirely.

    When you write string.split(separator: ""), you get an Array<Character>. You can do this more directly with just Array(string).

    It turns out that you didn't actually need an array of characters. You just needed something that you could call sorted() on, like Array(string).sorted(). You're in luck, because String is already a Collection<Character> (which is why that array initializer worked in the first places), and all collections of Comparable values are sortable. So all you needed was string.sorted()

    You then use .joined() on the result, to convert the Array<Character> back into a String. If you don't need a separator between the characters, the more straight-forward way to do that is just with the String initializer.

    So really, all you need is:

    let result = String(string.sorted())