Blog

Swift Tip: Extracting Parameters

In our latest Swift Talk series, Building a Form Library, we refactor a hand-coded settings form into a reusable, declarative library.

In Episode 98, we carry out a refactoring that has often proved useful. Given multiple functions with the same set of parameters, we can extract those parameters into a separate type.

We start with functions like this:

func hotspotForm(state: Hotspot, change: @escaping ((inout Hotspot) -> ()) -> (), pushViewController: @escaping (UIViewController) -> ()) -> ([Section], Observer) {
  // ...
}

func passwordForm(state: Hotspot, change: @escaping ((inout Hotspot) -> ()) -> (), pushViewController: @escaping (UIViewController) -> ()) -> ([Section], Observer) {
  // ...
}

In the code above, we can see the three parameters are repeated in both functions. To refactor the code, we group all three into a single struct:

struct RenderingContext<State> {
    let state: State
    let change: ((inout State) -> ()) -> ()
    let pushViewController: (UIViewController) -> ()
}

This makes our function definitions much shorter:

func hotspotForm(_ context: RenderingContext<Hotspot>) -> ([Section], Observer) {
  // ...
}

func passwordForm(_ context: RenderingContext<Hotspot>) -> ([Section], Observer) {
  // ...
}

As an additional benefit, it is now possible to extend our struct with properties and methods.

In previous episodes, you can see other examples where we extract repeating parameters into separate types. In our very first episode, we combined the URL and parsing code for a network request into a Resource struct. In Episode 27, we combined a notification’s name and parsing code into a struct for type-safe notifications.

When you find yourself writing multiple methods or functions that take a similar set of parameters, you can do the same thing. Group them together into a struct, enum, or class, and see if it makes your code simpler.

In a future episode of Swift Talk, we’ll also show how to simplify the return type. To watch all our episodes, you can subscribe. 👍

Stay up-to-date with our newsletter or follow us on Twitter.

Back to the Blog

recent posts