33
var numbers = "Hello,Goodbye,Hi,Bye"
var numbersArr = numbers.componentsSeparatedByString(",")

//["Hello"."Goodbye","Hi","Bye"]

Above is a basic representation of what I'm trying to do. I'm trying to use componentsSeparatedByString() to split a string with commas into an array, where each of the components of the array are between each of the commas from the original strings.

I am using IBM Swift Sandbox (Sorry, I'm on windows :) ), and in Swift 3.0, I am getting this error message:

value of type 'String' has no member 'componentsSeparatedByString'

I know Swift 3 is rather new, and is that is why I couldn't find ANY other references for this error.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Ethan Rappaport
  • 417
  • 1
  • 6
  • 14
  • This question is about Cocoa Foundation, not Swift. Are you even able to access Cocoa Foundation framework on Windows? – matt Jul 13 '16 at 18:03
  • 1
    I think it does (the IBM Swift Sandbox runs on Linux), but there is a also a "pure Swift" `split()` method which does not require Foundation, see for example http://stackoverflow.com/questions/25226940/swift-version-of-componentsseparatedbystring – Martin R Jul 13 '16 at 18:05

1 Answers1

104

It looks like there is a components(separatedBy:) on String:

import Foundation

let words = "apple binary cat delta echo".components(separatedBy: " ")
print(words)

enter image description here

IBM Playground link: http://swiftlang.ng.bluemix.net/#/repl/57868332b4e4e9971bf9f4e8

Steven Hepting
  • 12,394
  • 8
  • 40
  • 50
  • 3
    This method is provided by Foundation. You need to `import Foundation` to get this capability (note that `import UIKit` and `import Cocoa` both `import Foundation` for you). – vacawama Jul 13 '16 at 18:02
  • @vacawama But can he even do that on Windows? I don't think so. – matt Jul 13 '16 at 18:03
  • He's using the IBM Sandbox. This works there with `import Foundation`. – vacawama Jul 13 '16 at 18:03
  • It works perfectly as long as foundation has been imported, even on IBM Swift Sandbox on windows. Thanks so much!!! – Ethan Rappaport Jul 13 '16 at 21:41
  • Thanks for this fix, there's a bug in the compiler Xcode 8, beta 6 that prompts a change to `componentsSeparatedByString(by:",")` and then suggests you change it back again! So this was great to find. – sketchyTech Aug 30 '16 at 16:44