Markus Rautopuro
Markus Rautopuro

Reputation: 8365

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

Here's an example from HockeyApp that generates the following code:

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
}

Notice the repetition of BITHockeyManager.sharedHockeyManager() in each call. I'm looking for a syntax that does something like (pseudo code):

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

Is there a way to do this in Swift?

Edit: After writing this question I noticed that 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)
                   }

To use the corresponding syntax with HockeyApp would require modifying the BITHockeyManager class.

Upvotes: 1

Views: 208

Answers (2)

Markus Rautopuro
Markus Rautopuro

Reputation: 8365

You can always use the following approach, which is a little bit shorter, but still requires repetition of the variable manager:

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

Upvotes: 3

Martin R
Martin R

Reputation: 539685

I don't think that something like

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

is possible in Swift, but what you could do is to define a generic function

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

which simply calls the closure with the given item as the argument, and then take advantage of the "trailing closure syntax" and "shorthand argument name" $0:

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

Upvotes: 6

Related Questions