[英]In Swift, How can I declare a Dictionary where the key is a function? (does not conform to protocol 'Hashable')
I am trying to achieve this in Swift:我试图在 Swift 中实现这一点:
let dict : [ () -> () : String]
//error: type '() -> ()' does not conform to protocol 'Hashable'
//let dict : [ () -> () : String]
//^
But getting the error '() -> ()' does not conform to protocol 'Hashable'.但是得到错误 '() -> ()' 不符合协议 'Hashable'。 How can I fix that error?
我该如何修复该错误?
Edit: I am porting a Finite State Machine from Lua where the key happens to be a function.编辑:我正在从 Lua 移植一个有限状态机,其中键恰好是一个函数。 (I know that may be weird in any other language but for Lua is ok).
(我知道这在任何其他语言中都可能很奇怪,但对于 Lua 来说还可以)。 The Lua code:
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 }
I don't think you can fix it.我不认为你能解决它。 The key for a dictionary must conform to the
Hashable
protocol.字典的键必须符合
Hashable
协议。 That means that it has an Int hashValue property, and that it implements the ==
operator.这意味着它有一个 Int hashValue 属性,并且它实现了
==
运算符。 (See this link: https://developer.apple.com/documentation/swift/hashable ) (请参阅此链接: https : //developer.apple.com/documentation/swift/hashable )
Functions don't conform to the Hashable
protocol, so they can't be dictionary keys.函数不符合
Hashable
协议,因此它们不能是字典键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.