Find number of spaces in a string in Swift
Swift 5 or later
In Swift 5 we can use the new Character properties isWhitespace and isNewline
let str = "Hello, playground. Hello, playground !!!"
let spaceCount = str.reduce(0) { $1.isWhitespace && !$1.isNewline ? $0 + 1 : $0 }
print(spaceCount) // 4
If your intent is to count " "
only
let spaceCount = str.reduce(0) { $1 == " " ? $0 + 1 : $0 }
let title = "A sample string to test with."
let count = title.componentsSeparatedByString(" ").count - 1
print(count) // 5