Search code examples
stringvariablesswiftcharactersubtype

Swift - Character is not a subtype of string


myText = "word 1 / word 2"    
var testVar = split(myText, { $0 == "/"}, maxSplit: Int.max, allowEmptySlices: false)

This code works but it takes empty space "word 1 " when I use testVar[0]

when I write empty spaces

var testVar = split(myText, { $0 == " / "}, maxSplit: Int.max, allowEmptySlices: false)

I get an error: 'Character' is not a subtype of 'String'

Anyone who knows how to fix that?


Solution

  • The split() function only works on Swift strings by comparing each element of the string as a Character. To use a string to split a string, use .componentsSeparatedByString:

    var testVar = myText.componentsSeparatedByString(" / ")