【发布时间】:2021-12-19 03:53:51
【问题描述】:
我已经在 Swift 操场的一个类中声明了一个函数,但是当我尝试调用该函数以使用输入对其进行测试时,它的行为就像我试图再次定义该函数
func evaluate(_ input: String) {
print("Evaluating: \(input)")
let lexer = Lexer(input: input)
do {
let tokens = try lexer.lex()
print("Lexer output: \(tokens)")
} catch {
print("An error occurred: \(error)")
}
}
evaluate("10 + 3 + 5")
evaluate("1 + 2 + abcdefg")
它特别给出了错误:“函数声明体中的预期'{'” 我如何让它运行该功能??
这是完整的代码:
import Cocoa
enum Token {
case number(Int)
case plus
}
class Lexer {
enum Error: Swift.Error {
case invalidCharacter(Character)
}
let input: String
var position: String.Index
init(input: String) {
self.input = input
self.position = input.startIndex
}
func peek() -> Character? {
guard position < input.endIndex else {
return nil
}
return input[position]
}
func advance() {
assert(position < input.endIndex, "Cannot advance past endIndex!")
position = input.index(after: position)
}
func getNumber() -> Int {
var value = 0
while let nextCharacter = peek() {
switch nextCharacter {
case "0" ... "9":
let digitValue = Int(String(nextCharacter))!
value = 10*value + digitValue
advance()
default:
return value
}
}
}
func lex() throws -> [Token] {
var tokens = [Token]()
while let nextCharacter = peek() {
switch nextCharacter {
case "0" ... "9":
let value = getNumber()
tokens.append(.number(value))
case "+":
tokens.append(.plus)
advance()
case " ":
advance()
default:
throw Lexer.Error.invalidCharacter(nextCharacter)
}
}
return tokens
}
func evaluate(_ input: String) {
print("Evaluating: \(input)")
let lexer = Lexer(input: input)
do {
let tokens = try lexer.lex()
print("Lexer output: \(tokens)")
} catch {
print("An error occurred: \(error)")
}
}
evaluate("10 + 3 + 5")
evaluate("1 + 2 + abcdefg")
}
【问题讨论】:
-
除了这个之外肯定还有更多。如果我将
Lexer存根并按照编写的方式运行您的代码,它会编译并运行良好。有时 Playgrounds 会变得有点有趣——关闭和重新打开有时会有所帮助。 -
@jnpdx 我添加了其余的代码,我也退出了 xcode 并重新打开它,仍然得到同样的错误。我觉得我错过了一些简单的事情
标签: swift macos swift-playground