测试 Swift 中双引号字符的字符串

Testing string for double quote characters in Swift

我正在尝试使用以下代码在 swift 字符串类型中查找双引号字符:

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

if 语句永远不会捕获字符串中的双引号。

我正在使用 Xcode 7.3.1

有什么意见建议吗?

我认为代码甚至不应该编译? (假设 string 确实是一个字符串。)

试试这个。似乎对我有用(相同的 Xcode 版本):

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

取决于你想做什么:

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 {  == "\"" }
                .map { [=10=].0 }
print(indexes)