在Swift中,如何声明一个键为函数的Dictionary? (不符合协议“哈希”)

时间:2018-09-08 00:15:50

标签: swift function dictionary pointers key

我正在尝试在Swift中实现这一目标:

let dict : [ () -> () : String]
//error: type '() -> ()' does not conform to protocol 'Hashable'
//let dict : [ () -> () : String]
//^

但是出现错误'()->()'不符合协议'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 } 

1 个答案:

答案 0 :(得分:1)

我认为您不能修复它。字典的密钥必须符合2018_06_02_023820_create_role_user_table协议。这意味着它具有Int hashValue属性,并且实现了Hashable运算符。 (请参阅此链接:https://developer.apple.com/documentation/swift/hashable

函数不符合==协议,因此它们不能成为字典键。