在Swift中调用可选函数
发布时间:2020-12-14 04:48:49 所属栏目:百科 来源:网络整理
导读:我正试图找出一种通过数字动态调用方法的方法.这是我正在做的简化版本. 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: REP
我正试图找出一种通过数字动态调用方法的方法.这是我正在做的简化版本.
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]?() ~~~~^~~ 如果我跑了 func a() {} func b() {} let f = [0: a,1: b] f[0]?() 直接没有包含类,它按预期工作.这是怎么回事? 解决方法
这真的很有趣!我注意到,如果我将函数定义移到类之外但其他所有内容保持不变,那么第一部分代码就可以了.从错误消息中我得出结论,当在类中声明函数时,需要使用类的实例调用它们.当您在类中调用()时,编译器会自动将其解释为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) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |