如何在 Swift 中用较少重复的代码进行连续的方法调用?

How to make successive method calls with less repetitive code in Swift?

这是 HockeyApp 中生成以下代码的示例:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    BITHockeyManager.sharedHockeyManager().configureWithIdentifier(API_KEY)
    BITHockeyManager.sharedHockeyManager().disableCrashManager = true
    BITHockeyManager.sharedHockeyManager().startManager()
    BITHockeyManager.sharedHockeyManager().authenticator.authenticateInstallation()

    return true
}

注意在每次调用中重复 BITHockeyManager.sharedHockeyManager()。我正在寻找一种类似于(伪代码)的语法:

with BITHockeyManager.sharedHockeyManager() do {
    .configureWithIdentifier(API_KEY)
    .disableCrashManager = true
    .startManager()
    .authenticator.authenticateInstallation()
}

有没有办法在 Swift 中做到这一点?

编辑: 写完这个问题后我注意到 Alamofire is using "chainable methods" , which actually is originally what I was looking for. This allows a neat syntax, as follows (code from http://nshipster.com/alamofire/):

Alamofire.request(.GET, "http://httpbin.org/get")
         .response { (request, response, data, error) in
                     println(request)
                     println(response)
                     println(error)
                   }

要在 HockeyApp 中使用相应的语法,需要修改 BITHockeyManager class。

我不认为

with BITHockeyManager.sharedHockeyManager() do {
    .configureWithIdentifier(API_KEY)
    .disableCrashManager = true
    // ...
}

在 Swift 中是可能的,但是您 可以 做的是定义一个通用函数

func with<T>(item : T, closure : T -> Void) {
    closure(item)
}

它简单地以给定的项目作为参数调用闭包, 然后利用 "trailing closure syntax" 和 "shorthand argument name" [=13=]:

with( BITHockeyManager.sharedHockeyManager() ) {
    [=12=].configureWithIdentifier(API_KEY)
    [=12=].disableCrashManager = true
    // ...
}

您始终可以使用以下方法,它稍微短一些,但仍然需要重复变量 manager:

let manager = BITHockeyManager.sharedHockeyManager()
manager.configureWithIdentifier(API_KEY)
manager.disableCrashManager = true
manager.startManager()
manager.authenticator.authenticateInstallation()