How to use NSScanner?

Ziltoid’s solution works, but it’s more code than you need.

I wouldn’t bother instantiating an NSScanner for the given situation. NSCharacterSet and NSString give you all you need:

    NSString *logString = @"user logged (3 attempts)";
    NSString *digits = [logString stringByTrimmingCharactersInSet:
         [[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
    NSLog(@"Attempts: %i", [digits intValue]);

or in Swift:

    let logString = "user logged (3 attempts)"
    let nonDigits = NSCharacterSet.decimalDigitCharacterSet().invertedSet
    let digits : NSString = logString.stringByTrimmingCharactersInSet(nonDigits)
    NSLog("Attempts: %i", digits.intValue)

Leave a Comment