How to split a string into an array of substrings in Swift?
Hi everyone! I just started learning Swift and ran into a problem. I need to split a string into an array by a specific delimiter. For example, I have a string:
```swift
let data = "apple,banana,grape,orange"
```
I want to get an array: `["apple", "banana", "grape", "orange"]`.
In other languages (Python, JavaScript), I'm used to using `split()` or `split(",")`, but in Swift it doesn't work that way. I tried writing:
```swift
let result = data.split(",") // Error: No 'split' member
```
or
```swift
let result = data.components(separatedBy: ",") // Seems to work, but returns [String]
```
But I'm not sure if this is the correct approach. I've also heard about some `NSString` methods, but they seem outdated. Please tell me how to properly and Swift-idiomatically split a string.
No answers yet.
Log in to leave an answer