Swift 3 printing the value of String.CharacterView.Index


func evaluate(input: String) {
print(“Evaluating: (input)”)

let lexer = Lexer(input: input)
// This would allow ignoring the error without trapping if an error occurs
// guard let tokens = try? lexer.lex() else {
// print(“Lexing failed, but I don’t know why”)
// return
// }

do {
let tokens = try lexer.lex()
print(“Lexer output: (tokens)”)

let parser = Parser(tokens: tokens)
let result = try parser.parse()
print("Parser output: \(result)")

} catch Lexer.myError.InvalidCharacter(let character) {
print(“Input contained an invalid character at index (lexer.position): (character)”)
} catch Parser.myError.UnexpectedEndOfInput {
print(“Unexpected end of input during parsing at index (lexer.position)”)
} catch Parser.myError.InvalidToken(let token) {
print(“Invalid token during parsing at index (lexer.position): (token)”)
} catch { // catches any remaining errors to fulfill requirement of exhaustive handling
print(“An error occurred: (error)”)
} // end evaluate

evaluate(input: “10a + 3”)

the result is:
Evaluating: 10a + 3
Input contained an invalid character at index Index(_base: Swift.String.UnicodeScalarView.Index(_position: 2), _countUTF16: 1): a

I can’t seem to find a way to print the value as a simple integer. Keep getting entire string that includes the value I’m trying to get at.


What exactly are you trying to do?

If you just want to extract the 10 from the input 10a + 3 and print it after catching the exception, take a look at the Scanner class reference if you are curious.

Here is a tiny example for telling whether a string starts with an integer.

let input = "17Zoo Lane"
let s = Scanner (string:input)
var v = 0
if s.scanInt (&v) {
    print ("\(input): starts with integer \(v)")
else {
    print ("\(input): does not start with an integer.")