簡體   English   中英

如何在Swift中聲明作為屬性名稱的函數參數

[英]How to declare in Swift a function parameter that is a property name

我想要一個可以在運行時訪問另一個類中的指定屬性的類。 我猜測如果我將閉包或函數作為參數傳遞進來是可能的。 例如:

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
}

然后在創建X時傳遞getPosition

但是是否有一些語法可以將whereAmI作為函數名傳遞呢? 然后,在action方法中,我可以做:

thing.pointFunction

您只需要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 ,無論如何它還是有點尷尬,或者您必須具有兩個這樣的init:

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

因此,實際上,在大多數情況下, {$0.whereAmI}方法比咖喱方法更容易使用,而這正是我在這里建議的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM