Typealias

Introduction

Welcome to the last lesson of The Swift Fundamentals. You’ve come a long way. You will learn how to create fake names for anything. This lesson should be nice and short.

Problem

The parameters are unreadable and boring

Typealias: A false or assumed identity. - Oxford Dictionary

Typealias for String

Instead of using String, let us create a fake name for String.

  1. typealias Name = String
  2. func insertName(name: Name) {}
  3. insertName(name: "Bob Lee")

Typealias for Custom Class

  1. class Employee {}
  2. typealias MyEmployees = [Employee]
  3. func listEmployees(enterEmployees: MyEmployees) {}

Typealias for Tuple

  1. typealias GridPoint = (Int, Int)
  2. func enterPoint(grid: GridPoint) {
  3. print("You've entered, \(grid.0) and \(grid.1)")
  4. }
  5. enterPoint(grid: (4, 2))

Type Definition

Let’s review how to initialize Array, Dictionary, and Optional.

Array Type

  1. let arrayOne: Array<String> = ["Bob", "Bobby"] // Generic Struct
  2. let arrayTwo: [String] = ["Bob", "Bobby"]

Dictionary Type

  1. let dictTwo: Dictionary<String, Int> = ["Alex": 31, "Paul": 39] // Generic Struct
  2. let dictOne: [String: Int] = ["Alex": 31, "Paul": 39]

Optional Type

  1. var optionalOne: String?
  2. var optionalTwo: Optional<String> // Generic Enum

You will learn more about optionals in Chapter 8: Advanced Enums.

Source Code

1012_typealias.playground

Conclusion

That’s it. You’ve learned how fake.