Swift typealias

Allows us to provide a new name to an existing type.

Swift typealias

The aliased name can be used instead of the existing type. It doesn't create a new type, it simply provides a new name to an existing type.

Why use typealias

  1. Readability of our code.
  2. Combining protocols.
  3. Used with generic parameters.
  4. For declaring closures.

How to create typealias

Typealias is declared using the keyword typealias as:

typealias name = <existing-type>

Disadvantages of using typealias

  • It can become extremely messy when using typealias throughout the codebase
  • It can add an additional step when collaborating on larger projects as programmers will need to check the type

Typealias can be used with most types, e.g;

  • Built-in types: String, Int
  • User defined: class, struct, enum
  • Complex types: closures

Few exmaples of using typealias in practical iOS development

typealias CompletionHandler = (String) -> (String)

func taskFunc(completion: CompletionHandler) {
}

In the above Swift code typealias is being used to name a closure and use the named alias in a function argument.

typealias TransitionDelegate = UIViewController & UIViewControllerTransitioningDelegate

class ViewController: TransitionDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    
    // MARK:- UIViewControllerTransitioningDelegate methods
    // FIXME: the delegate method implementation goes here
}

In the above Swift code typealias is being used to make a delegate conform to multiple types.

typealias Info = [String: Any]
let userInfo: Info = ["name": "Harish"]

In the above Swift code typealias is being used to make a simple alias for a dictionary which can be used in multiple places.

Conclusion

Initialy you may find typealias very simple, however once you dive in and take a closer look, it turns out that they’re quite capable in many cases. While over-using them could make our code base harder to navigate, making selective use of them can result into more simplified code.

Tagged with: