I was wondering why this works (notice I am using NSString types):
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"
but if I try to use "String" types instead of "NSString", this will not compile:
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)
The error says "Cannot convert the expression's type 'BOOL' to type 'inout String?' on the scanUpToString line. I'm not sure what BOOL it is even referring to.
So, does NSScanner not work with Swift String types? Is there a new command I should be using instead?
The second parameter of the scanUpToString
method must be a pointer to a NSString
. The other params can be String
. This code will work:
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 "
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With