Does NSScanner work with Swift Strings?
Asked Answered
K

1

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?

Kowalewski answered 14/6, 2014 at 20:44 Comment(0)
J
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 "
Judgemade answered 14/6, 2014 at 21:2 Comment(2)
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.Kowalewski
@Kowalewski 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.Acetylide

© 2022 - 2024 — McMap. All rights reserved.