我正在尝试找出一种通过编号动态调用方法的方法。以下是我正在做的简化版本。
当我在 Playground 中运行时,我得到了以下结果。
没有包含类时,可以直接使用,它的效果如预期。出了什么问题?
class C {
func a() {}
func b() {}
let f = [0: a, 1: b]
func call(n: Int) {
f[n]?()
}
}
let c = C()
c.call(0)
当我在 Playground 中运行时,我得到了以下结果。
Playground execution failed: error: <REPL>:10:13: error: could not find an overload for 'subscript' that accepts the supplied arguments
f[n]?()
~~~~^~~
然而如果我运行
func a() {}
func b() {}
let f = [0: a, 1: b]
f[0]?()
没有包含类时,可以直接使用,它的效果如预期。出了什么问题?
f
实际上是类型为Dictionary<Int, C -> () -> ()>
的字典。不过我仍然会使用可选链,并使用f[n]?(self)()
。 - Jean-Philippe Pellet