Search code examples
swiftstringif-statementdouble-quotes

Testing string for double quote characters in Swift


I am trying to find double quote characters in a swift String type with the following code:

for char in string {
    if char == "\"" {
        debugPrint("I have found a double quote")
    }
}

The if statement never catches the double quote in the string.

I am using Xcode 7.3.1

Any suggestions of comments?


Solution

  • Depending on what you want to do:

    let str = "Hello \"World\""
    
    // If you simply want to know if the string has a double quote
    if str.containsString("\"") {
        print("String contains a double quote")
    }
    
    // If you want to know index of the first double quote
    if let range = str.rangeOfString("\"") {
        print("Found double quote at", range.startIndex)
    }
    
    // If you want to know the indexes of all double quotes
    let indexes = str.characters.enumerate()
                    .filter { $1 == "\"" }
                    .map { $0.0 }
    print(indexes)