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

标签 swift function dictionary pointers key

我正在尝试在 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/

相关文章:

ios - 如何在滚动时停止在 Collection View 中重新加载服务器图像?

ios - 为 Swift UI View 创建自定义修饰符

c++ - 当插入太多元素时,std::map 会自动调整大小吗?

javascript - `.map` 不是用于循环吗?

iOS:在 uicollectionview 中添加 UIProgressView 以显示上传到 firebase 存储的上传百分比

ios - 快速将自定义类型转换为 CGFloat

function - 使用 F# 的“选项<unit->unit> 类型和等式”

javascript - 将此 JSON 重写为 jQuery data() 的更好方法是什么?

jquery - 获取元素偏移位置并做一些事情

php - 如何使用 php 字典执行 foreach 循环?