Search code examples
swiftsvgnsscanner

Swift NSScanner doesn't return start character


I'm scanning an SVG path string, and using NSScanner to try and break it up into it's components. When it runs though I get the components, but I'm not getting back the "type"

For example: "m 186.14021,456.15955 3.19716,8.75681 c 1.78393"

Should return: "m 186.14021,456.15955 3.19716,8.75681"

Actual Result: "186.14021,456.15955 3.19716,8.75681"

Any ideas where my code is going awry?

import UIKit

let whitespaceAndPunctuationSet = NSMutableCharacterSet.whitespaceAndNewlineCharacterSet()
whitespaceAndPunctuationSet.formUnionWithCharacterSet(NSCharacterSet.punctuationCharacterSet())


var str = "m 186.14021,456.15955 3.19716,8.75681 c 1.78393,0.93528 30.33822,25.2032 27.48643,47.35972 -4.11654,31.98273 -39.24645,39.28157 -59.94003,28.99354 -20.69358,-10.28804 -17.12572,-56.58417 -14.98501,-58.45472 2.14072,-1.87055 24.97501,-80.4337 44.24145,-26.65535 z"
let characterSet = NSCharacterSet(charactersInString: "mlhvcsqtaz")
let aScanner = NSScanner(string: str)
aScanner.charactersToBeSkipped = whitespaceAndPunctuationSet

while aScanner.atEnd == false
{
    var testString:NSString?

    aScanner.scanUpToCharactersFromSet(characterSet, intoString: &testString)

    aScanner.scanCharactersFromSet(characterSet, intoString: nil)

    print(testString)
}

Solution

  • Ok, this seems to work:

    import UIKit
    
    let whitespaceAndPunctuationSet = NSMutableCharacterSet.whitespaceAndNewlineCharacterSet()
    whitespaceAndPunctuationSet.formUnionWithCharacterSet(NSCharacterSet.punctuationCharacterSet())
    
    
    var str = "m 186.14021,456.15955 3.19716,8.75681 c 1.78393,0.93528 30.33822,25.2032 27.48643,47.35972 -4.11654,31.98273 -39.24645,39.28157 -59.94003,28.99354 -20.69358,-10.28804 -17.12572,-56.58417 -14.98501,-58.45472 2.14072,-1.87055 24.97501,-80.4337 44.24145,-26.65535 z"
    let characterSet = NSCharacterSet(charactersInString: "mlhvcsqtaz")
    let aScanner = NSScanner(string: str)
    aScanner.charactersToBeSkipped = whitespaceAndPunctuationSet
    
    while aScanner.atEnd == false
    {
        var testString:NSString?
        var controlChar:NSString?
    
        aScanner.scanCharactersFromSet(characterSet, intoString: &controlChar)
    
        aScanner.scanUpToCharactersFromSet(characterSet, intoString: &testString)
    
        print(controlChar)
        print(testString)
    }