【问题标题】:Swift - get reference to a function with same name but different parametersSwift - 获取对具有相同名称但不同参数的函数的引用
【发布时间】:2015-04-05 10:12:33
【问题描述】:

我正在尝试获取对这样一个函数的引用:

class Toto {
    func toto() { println("f1") }
    func toto(aString: String) { println("f2") }
}

var aToto: Toto = Toto()
var f1 = aToto.dynamicType.toto

我有以下错误:Ambiguous use of toto

如何获取指定参数的函数?

【问题讨论】:

  • 请注意,aToto.dynamicType.toto 返回一个以类实例作为其第一个参数的柯里化函数,因为您通过其类型 (aToto.dynamicType) 引用它。 aToto.toto 的等价物是 Toto.toto(aToto)aToto.dynamicType.toto(aToto)

标签: objective-c function swift dynamictype


【解决方案1】:

由于Toto有两个同名但签名不同的方法, 你必须指定你想要哪一个:

let f1 = aToto.toto as () -> Void
let f2 = aToto.toto as (String) -> Void

f1()         // Output: f1
f2("foo")    // Output: f2

或者(正如@Antonio 正确指出的那样):

let f1: () -> Void     = aToto.toto
let f2: String -> Void = aToto.toto

如果您需要将类的实例作为 curried 函数 那么第一个论点 你可以以同样的方式进行,只是签名不同 (比较@Antonios 对您的问题的评论):

let cf1: Toto -> () -> Void       = aToto.dynamicType.toto
let cf2: Toto -> (String) -> Void = aToto.dynamicType.toto

cf1(aToto)()         // Output: f1
cf2(aToto)("bar")    // Output: f2

【讨论】:

  • 相当于let f1: Void -> Void = aToto.totolet f2: String -> Void = aToto.toto
  • @Antonio:你说得对,谢谢。 (实际上我是先尝试过的,但一定是出错了,因为它最初没有编译。)
  • aToto.totoaToto.dynamicType.toto 之间没有区别吗?第一个返回() -> Void,而第二个返回Toto -> () -> Void。我有一个将第二种类型作为参数的库,所以我认为我需要使用dynamicType 的东西来获取我的函数。但是aToto.dynamicType.toto as (String) -> Void 返回以下错误:String is not a subtype of Toto
  • 对!谢谢你们的解释;)
  • @MartinR 你知道区分参数类型相同但外部参数名称不同的方法的方法吗?这在委托方法的情况下很常见。在类型声明中包含参数名称似乎没有帮助。
猜你喜欢
  • 1970-01-01
  • 2018-11-18
  • 1970-01-01
  • 2017-05-13
  • 2015-08-18
  • 2010-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多