在Swift中调用可选函数
我正试图找到一种方法,通过数字动态调用方法。这是我正在做的一个简化版本在Swift中调用可选函数,swift,optional,Swift,Optional,我正试图找到一种方法,通过数字动态调用方法。这是我正在做的一个简化版本 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 execution failed: error: <REPL>:10:13: err
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 execution failed: error: <REPL>:10:13: error: could not find an overload for 'subscript' that accepts the supplied arguments
f[n]?()
~~~~^~~
直接使用,不包含类,它可以按预期工作。发生了什么事?这真的很有趣!我注意到,如果我将函数定义移到类之外,但保持所有其他内容不变,那么您的第一段代码运行良好。从错误消息中,我可以得出结论,当函数在类中声明时,需要使用类的实例调用它们。当您在类内部调用
a()
时,编译器会自动将其解释为self.a()
。但是,当函数存储在变量(f[0]
、f[1]
等)中时,需要首先向它传递一个类C
(self
)的实例。这项工作:
class C {
func a() {println("in a")}
func b() {println("in b")}
let f = [0: a, 1: b]
func call(n: Int) {
a() // works because it's auto-translated to self.a()
f[n]?(self)() // works because self is passed in manually
}
}
let c = C()
c.call(0)
是的
f
实际上属于Dictionary()->()>
类型。尽管如此,我仍然会使用可选链接和f[n]?(self)(
。很好的选择,我没有故意切换。现在修好了!猛冲你是怎么或者从哪里得到信息的?很好。这是一种非常有趣的展示方式。
class C {
func a() {println("in a")}
func b() {println("in b")}
let f = [0: a, 1: b]
func call(n: Int) {
a() // works because it's auto-translated to self.a()
f[n]?(self)() // works because self is passed in manually
}
}
let c = C()
c.call(0)