9

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?

Narwhal
  • 744
  • 1
  • 8
  • 22

1 Answers1

15

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 "
Adam
  • 26,549
  • 8
  • 62
  • 79
  • So, out of curiosity, does that makes sense then? Do you expect it will remain that way even when Swift goes production? Seems strange to me that a string function any sort would not be able to output a Swift String type. – Narwhal Jun 14 '14 at 23:32
  • 1
    @Narwhal It makes sense because such libraries are all in OBJC, and being regarded as a legacy. And inter-op with legacy is always ugly, weird and hard. – eonil Nov 10 '14 at 16:59