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
:
use
componentsseparatedbystring
:"ab cd".componentsseparatedbystring(" ") // ["ab", "cd"]
as pointed out @dawg, requires
import foundation
.instead of calling
split
onstring
, use characters ofstring
.characters
property returnsstring.characterview
, conformscollectiontype
:"😀 🇬🇧".characters.split(" ").map(string.init) // ["😀", "🇬🇧"]
make
string
conformcollectiontype
:extension string : collectiontype {} "w,x,y,z".split(",") // ["w", "x", "y", "z"]
although, since apple made decision remove
string
's conformancecollectiontype
seems more sensible stick options 1 or two.
in swift 3, in options 1 , 2 respectively:
componentsseparatedbystring(:)
has been renamedcomponents(separatedby:)
.split(:)
has been renamedsplit(separator:)
.
Comments
Post a Comment