打印'String.CharacterView.Index'值的值

时间:2016-11-30 22:13:53

标签: string swift3

在类词法分析器中,变量“position”定义为:

class Lexer {
  enum myError: Error {
    case InvalidCharacter(Character,String.CharacterView.Index)
  }
  let input: String.CharacterView
  var position: String.CharacterView.Index
  init(input: String) {
    self.input = input.characters
    self.position = self.input.startIndex
  }

在输出代码中:

func evaluate(input: String) {
print("Evaluating: (input)")

let lexer = Lexer(input: input)

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")

结果是:

评估:10a + 3 索引Index(base:Swift.String.UnicodeScalarView.Index(position:2),_ counttF16:1)中的输入包含无效字符:a

我似乎无法找到将值打印为简单整数的方法。继续获取一个错误字符串,甚至包括我想要获得的值。

1 个答案:

答案 0 :(得分:0)

在Swift中,String.CharacterView.Index不是整数,因此您不能指望打印输出是一个简单的整数

如果您需要打印出代表String.CharacterView.Index的整数值,您明确需要计算它。

例如:

class Lexer {
    //...

    var offset: Int {
        return self.input.distance(from: self.input.startIndex, to: self.position)
    }
}

定义一个返回Int并使用lexer.offset代替lexer.position的计算属性。