我正在尝试在 Swift 中实现这一目标:
let dict : [ () -> () : String]
//error: type '() -> ()' does not conform to protocol 'Hashable'
//let dict : [ () -> () : String]
//^
但是得到错误 '() -> ()' 不符合协议(protocol) 'Hashable'。我该如何修复该错误?
编辑: 我正在从 Lua 移植一个有限状态机,其中的键恰好是一个函数。 (我知道这在任何其他语言中可能很奇怪,但对于 Lua 来说没问题)。 Lua代码:
local machine = {}
machine [Entry] = {loop = Entry, go = Another, gosub = sub }
machine [Another] = {go = Entry, loop = Another, next = Next }
machine [Next] = {startAgain = Entry }
machine [sub] = {out = Entry, next = Next, gosub = indoor, goOutDoor = outdoor }
machine [indoor] = {out = sub, next = sub }
machine [outdoor] = {next = sub }
最佳答案
我不认为你可以修复它。字典的键必须符合 Hashable
协议(protocol)。这意味着它有一个 Int hashValue 属性,并且它实现了 ==
运算符。 (查看此链接:https://developer.apple.com/documentation/swift/hashable)
函数不符合 Hashable
协议(protocol),因此它们不能是字典键。
关于swift - 在 Swift 中,如何声明键为函数的字典? (不符合协议(protocol) 'Hashable' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52230946/