NSScanner是否适用于Swift Strings?

时间:2014-06-14 20:44:25

标签: nsstring swift ios8 xcode6 nsscanner

我想知道为什么会这样(注意我使用的是NSString类型):

    let stringToSearch:NSString = "I want to make a cake and then prepare coffee"
    let searchTerm:NSString = "cake"
    let scanner = NSScanner(string: stringToSearch)
    var result:NSString? = nil
    scanner.scanUpToString(searchTerm, intoString:&result)
    println(result) // correctly outputs "I want to make a"

但如果我尝试使用" String"类型而不是" NSString",这将无法编译:

    let altStringToSearch:String = "I want to make a cake and then prepare coffee"
    let altSearchTerm:String = "cake"
    let altScanner = NSScanner(string: altStringToSearch)
    var altResult:String? = nil
    altScanner.scanUpToString(altSearchTerm, intoString:&altResult)
    println(result)

错误说"无法转换表达式' BOOL'键入' inout String?'在scanUpToString行上。我不确定它甚至指的是BOOL。

那么,NSScanner无法使用Swift String类型吗?是否有我应该使用的新命令?

1 个答案:

答案 0 :(得分:14)

scanUpToString方法的第二个参数必须是指向NSString的指针。其他参数可以是String。这段代码可以使用:

let altStringToSearch:String = "I want to make a cake and then prepare coffee"
let altSearchTerm:String = "cake"
let altScanner = NSScanner(string: altStringToSearch)
var altResult:NSString?
altScanner.scanUpToString(altSearchTerm, intoString:&altResult) // altResult : "I want to make a "