2015-06-02 73 views
1

我希望有一个类可以在运行时访问另一个类中的指定属性。我猜测如果我通过一个闭包或函数作为参数是可能的。例如:如何在Swift中声明属性名称的函数参数

class X { 

    let pointFunction : (Thing) -> (CGPoint) 

    init(pointFunction : (Thing) -> (CGPoint)) { 
     self.pointFunction = pointFunction 
    } 

    func action(#thing : Thing) { 
     var p = pointFunction(thing) 
     ... 
    } 
} 

class func getPosition(thing : Thing) -> CGPoint { 
    return thing.whereAmI 
} 

创建十

时不过是有一些语法,我可以在whereAmI只传递作为函数名称,然后通过getPosition?然后,在action方法我可以这样做:

thing.pointFunction 
+0

什么是“事”?它是一种类型还是需要使用多种类型? – ABakerSmith

+0

它将是一个固定类型的类X. – rghome

+0

如果你使它NSObject你可以使用KVC –

回答

2

你只需要一个Thing->CGPoint。函数文本是作为函数有一样好:

let x = X(pointFunction: {$0.whereAmI}) 

如果你能承诺whereAmI是一个方法而不是一个性质,那么你可以做一些其他技巧(见http://oleb.net/blog/2014/07/swift-instance-methods-curried-functions/),但它仅适用与方法。不可思议的IMO Swift属性不是方法。如果他们是,你可以通过Thing.whereAmI

这就是说,你那么必须改变你的init采取Thing ->() -> CGPoint,这是一个稍微尴尬呢,还是你必须有两个inits这样的:

init(pointFunction : (Thing) -> (CGPoint)) { 
    self.pointFunction = pointFunction 
} 
convenience init(pointMethod : Thing ->() -> CGPoint) { 
    self.init(pointFunction: {pointMethod($0)()}) 
} 

所以真的,在大多数情况下,使用{$0.whereAmI}的方法比curried方法更容易使用,正是我在这里推荐的。

+0

几乎可以工作,但我得到一个编译器错误的实际thing.PointFunction调用。应该是什么样子? – rghome

+0

thing.pointFunction()。这是一个功能。你必须打电话给它。 –

+0

我错过了一些东西。它不用括号进行编译。说“东西没有名为pointFunction的成员”。对不起 - 有一个原因http://fuckingclosuresyntax.com存在。 – rghome

相关问题