How to split string? Value of type 'String' has no member 'components'

While going through the very basics of Swift, in a xcode playground I tried to split a string by the new line character so followed a few tips I found online:

let lines = text.components(separatedBy: "\n")

But unfortunately I get Value of type 'String' has no member 'components'

It's an NSString method, so you need to import Foundation.


Thanks a lot for looking @Lantua. Unfortunately, I didn't figure that out myself, I did try to import NSString, what should I learn to identify by myself what I need to "import" when using Swift?

Edit, note: It is referenced in the documentation ( but wasn't clear that Foundation is a package. I guess I can look into the sidebar where its mentioned in the "Framework"?


Yes, you can check under Framework section, more or less. You import a module (Foundation) for everything therein. You can also selectively import a smaller portion of it, like so:

import Foundation.NSString

I think there's a distinction between module & framework, but it's not really important for this usage.


Ok thanks!

you need to also write what type you're importing, i.e. class, enum, struct, typealias...

import class Foundation.NSString

Both works, I tried :3.

Edit, on Swift Playground

Huh. Is this a difference between linux and mac?

$ swift run
/home/cukier/Desktop/śmieci z pulpitu/lsp/foo/Sources/foo/main.swift:1:8: error: no such module 'Foundation.NSString'
import Foundation.NSString
[1/2] Compiling foo main.swift
1 Like

It can work without the symbol type if there’s a sub module defined by that name (in the modulemap I believe). Maybe that is different between macOS and Linux

1 Like

The native splitting method is text.split(separator: "\n").