Fix Swift error: value of type ‘String’ has no member ‘components’
In this tutorial, I will show you when error: value of type ‘String’ has no member ‘components’ this error occurs and how to fix this error in Swift.
Before jumping to the error solving it’s good to know why and when this error happens.
Let’s see an example first:
let myString = "Hello, I am a string" print(myString.components(separatedBy:"s"))
Output:
error: value of type 'String' has no member 'components'
But my expectation was not like this.
This happens because I am using .components
method on a string.
But if you read the official documentation then you will find out that, this is NSString
method. (I will discuss more about NSString in another tutorial)
In order to use .components
method here, we can simply import another module which is known as Foundation
.
Solution
Solution to that error: import Foundation
import Foundation let myString = "Hello, I am a string" print(myString.components(separatedBy:"s"))
Output:
["Hello, I am a ", "tring"]
Have you ever thought that you are importing the whole Foundation
module just to use NSString
?
It’s better just to import the necessary part of a module. So I would suggest you to use import Foundation.NSString
But in some compilers, it may not work. It’s better to check it yourself.
Leave a Reply