【发布时间】:2020-10-29 06:57:39
【问题描述】:
我正在编写一个解析器类,它希望以特定顺序读取一系列标记。其语法中的某些产品具有可选的非终端,因此我想做一个通用的“可能”函数,可以将负责将非终端解析为回调的函数传递给该函数。通常,该函数会在失败时抛出错误,但由于在某些情况下它是可选的,因此该 may 函数会抑制错误。但是,Swift 提供了错误“表达式类型在没有更多上下文的情况下不明确”,我无法找出正确的强制转换和/或类型来消除歧义。
这是我能够编写的用于重现错误的最少代码量:
public struct VariableDeclaration {
public let identifier: Identifier
public let type: String?
}
public struct Identifier { }
public class Parser {
public func parseVariableDeclaration() throws -> VariableDeclaration {
let identifier = try self.parseIdentifier()
let type = self.maybe(self.parseType)
return VariableDeclaration(identifier: identifier, type: type)
}
public func parseIdentifier() throws -> Identifier { return Identifier() }
public func parseType() throws -> String { return "" }
public func maybe<T>(_ callback: (Parser) -> () throws -> T) -> T? {
do {
return try callback(self)()
}
catch {
return nil
}
}
}
以下是我在消除有问题的行时的一些失败尝试:
let type: String? self.maybe(self.parseType)
let type = self.maybe(self.parseType) as String?
let type = self.maybe<String>(self.parseType)
【问题讨论】: