简体   繁体   中英

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:

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

But getting the error '() -> ()' does not conform to protocol '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. (I know that may be weird in any other language but for Lua is ok). The Lua code:

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. That means that it has an Int hashValue property, and that it implements the == operator. (See this link: https://developer.apple.com/documentation/swift/hashable )

Functions don't conform to the Hashable protocol, so they can't be dictionary keys.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM