我使用此RegEx进行检测:
let text = myText.substringWithRange(myText[0].rangeOfString("(?<=\")[^\"]+", options: .RegularExpressionSearch)!)
所以它完美无缺,但是当它无法找到它搜索的内容时就崩溃了!我怎么能假装呢?
我试过
if let text = ... {
...
}
在这种情况下,返回Initializer for conditional binding must have Optional type, not 'String'
。我怎么能假装崩溃?
答案 0 :(得分:1)
您尝试将Range<Index>
与rangeOfString("(?<=\")[^\"]+", options: .RegularExpressionSearch)!
解包,然后您需要将其测试为nil
。尝试这样做:
if let range = myText.rangeOfString("(?<=\")[^\"]+", options: .RegularExpressionSearch) {
let text = myText.substringWithRange(range)
...
}