2016-11-30 91 views
0

在類詞法分析器的值,變量「位置」定義爲:打印「String.CharacterView.Index」值

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 輸入包含在索引索引無效字符(鹼:Swift.String.UnicodeScalarView.Index(位置:2),_countUTF16:1):一個

我似乎無法找到一種方法來打印值作爲一個簡單的整數。繼續收到一個錯誤字符串,其中甚至包含我試圖獲取的值。

回答

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