在Swift中,如何声明键是函数的字典? (不符合协议'Hashable')

问题描述 投票:1回答:1

我试图在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 } 
swift function dictionary pointers key
1个回答
1
投票

我认为你无法修复它。字典的关键必须符合Hashable协议。这意味着它具有Int hashValue属性,并且它实现了==运算符。 (见链接:https://developer.apple.com/documentation/swift/hashable

函数不符合Hashable协议,因此它们不能是字典键。

© www.soinside.com 2019 - 2024. All rights reserved.