To iterate over words in a string in Swift, you can use the components(separatedBy:)
method to split the string into words, then use a loop to iterate over the resulting array.
In this example,
str
with a string value.components(separatedBy:)
method to split the string into an array of words using a space character as the separator.for
loop to iterate over each word in the array.import Foundation
let str = "Hello World from Swift"
let words = str.components(separatedBy: " ")
for word in words {
print(word)
}
Hello World from Swift
In this example,
str1
with a string value containing words separated by commas.components(separatedBy:)
method to split the string into an array of words using a comma as the separator.for
loop to iterate over each word in the array.import Foundation
let str1 = "apple,banana,orange,grape"
let words = str1.components(separatedBy: ",")
for word in words {
print(word)
}
apple banana orange grape
In this tutorial, we learned How to Iterate over Words in String in Swift language with well detailed examples.