swift2 - Using the split function in Swift 2 -


let's want split string empty space. code snippet works fine in swift 1.x. not work in swift 2 in xcode 7 beta 1.

var str = "hello bob" var foo = split(str) {$0 == " "} 

i following compiler error:

cannot invoke 'split' argument list of type '(string, (_) -> _) 

anyone know how call correctly?

updated: added note xcode 7 beta 1.

split method in extension of collectiontype which, of swift 2, string no longer conforms to. fortunately there other ways split string:

  1. use componentsseparatedbystring:

    "ab cd".componentsseparatedbystring(" ") // ["ab", "cd"] 

    as pointed out @dawg, requires import foundation.

  2. instead of calling split on string, use characters of string. characters property returns string.characterview, conforms collectiontype:

    "😀 🇬🇧".characters.split(" ").map(string.init) // ["😀", "🇬🇧"] 
  3. make string conform collectiontype:

    extension string : collectiontype {}  "w,x,y,z".split(",") // ["w", "x", "y", "z"] 

    although, since apple made decision remove string's conformance collectiontype seems more sensible stick options 1 or two.


in swift 3, in options 1 , 2 respectively:

  • componentsseparatedbystring(:) has been renamed components(separatedby:).
  • split(:) has been renamed split(separator:).

Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -