看完Ole的帖子http://oleb.net/blog/2014/07/swift-instance-methods-curried-functions/
据我了解,您可以在不同的上下文或范围内调用任何类的方法。如果我正确理解,则与javascript中的相同apply
或相同call
。
这是我尝试将其用于Observer模式的尝试。
我有一个问题self.method(self.context)(message)
,错误提示(Messaging) -> $T6 is not identical to 'Void'
protocol Messaging {
var message: String { get set }
}
class Observer {
var method: Messaging -> Void
var context: AnyObject
init(method: Messaging -> Void, context: AnyObject) {
self.method = method
self.context = context
}
func notify(message: Messaging) {
self.method(message)
//self.method(self.context)(message) // Houston, we have a problem
}
}
public class Message: Messaging {
var message: String
public init(message: String) {
self.message = message
}
}
class TestObserver {
func createAndNotifiy() {
var observer = Observer(method: self.handleMessage, context: self)
observer.notify(Message(message: "TestMessage"))
}
func handleMessage(message: Messaging) -> Void {
println(message.message)
}
}
var test = TestObserver()
test.createAndNotifiy()
内部notify
方法我试图在传递的上下文中调用传递的方法(我曾经用过context
,self
但是也可能是不同的上下文)
我的目标是使它适用于任何传入的上下文。
编辑:是我曾经传递过的功能,它会自动与该上下文相关联,例如Observer(method: self.handleMessage...
在这种情况下handleMessage
隐式/显式地绑定到该上下文,self
并且我真的不应该在意将其self
作为附加参数传递(作为上下文) ),导致自动在绑定对象的上下文中self.method(message)
调用method
?这是我的假设,期待有一个扎实的意见。
但无论如何仍然还是想知道在这种情况下如何使用咖喱的方法
self.methodname
(您正在使用的)和之间是有区别的Classname.methodname
。
前者在类的方法中调用时,将为您提供与该类实例绑定的函数。因此,如果您调用它,它将在该实例上被调用。
后者为您提供了一个咖喱函数,该函数将的任何实例作为参数Classname
,并返回绑定到该实例的新函数。在这一点上,该函数就像第一种情况(只有您可以将其绑定到所需的任何实例)。
这是一个示例,试图证明它更好一点:
class C {
private let _msg: String
init(msg: String) { _msg = msg }
func print() { println(_msg) }
func getPrinter() -> ()->() { return self.print }
}
let c = C(msg: "woo-hoo")
let f = c.getPrinter()
// f is of type ()->()
f() // prints "woo-hoo"
let d = C(msg: "way-hey")
let g = C.print
// g is of type (C)->()-(),
// you need to feed it a C:
g(c)() // prints "woo-hoo"
g(d)() // prints "way-hey"
// instead of calling immediately,
// you could store the return of g:
let h = g(c)
// at this point, f and h amount to the same thing:
// h is of type ()->()
h() // prints "woo-hoo"
最后,似乎您正在尝试使用AnyObject
,采用任何类型的类,并将其传递给您的咖喱实例方法。那将不会实现–咖喱方法将特别需要它所使用的类的类型。尝试喂其他东西没有好处。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句