Kinds of types

You may have heard that Functional Programming (FP) uses concepts of the category theory and type theory. This link is the reason why some people find FP closer to mathematics. Theoretically, category refers to a collection that contains the following:

  • A collection of objects (types in Swift)
  • A collection of morphisms, each of which ties two objects together (functions in Swift)
  • A notion of composition of the morphisms (function composition in Swift)

We have already discussed functions and function composition and now we are going to explore types.

It is possible to categorize types in four different ways:

  • Named versus compound types
  • Sum versus product types
  • Abstract versus concrete types
  • Value versus reference types

Any type that we can give a name to while we define it, is a named type. For instance, if we create a class named OurClass, any instance of OurClass will be of the OurClass type.

Function types and tuple types are compound types. A compound type may contain named types and other compound types. For instance, (String, (Double, Double)) is a compound type and in fact it is a tuple of String and another tuple of the (Double, Double) type. We can use named types and compound types in type annotation, identification, and aliasing.

Tuples and structs are product types or AND types. For instance, to create a User entity we will need to have name and age properties. Enums are sum types or OR types. For instance, a web API can either return a 2XX or 4XX or 5XX HTTP status code. We will talk about sum, product, and recursive types when we talk about algebraic data types in Chapter 4, Enumerations and Pattern Matching.

Types that the compiler can figure out their size at compile time and we can instantiate them are concrete. For instance, String, Int, and Double are concrete types. On the other hand, types that the compiler cannot figure out their size at compile time and we cannot instantiate them are abstract. Generics and protocols are examples of abstract types. Then there is type erasure that is a process to make abstract types concrete. We will talk about abstract types and type erasure in Chapter 5, Generics and Associated Type Protocols.

So far, we did not talk a lot about reference versus value types and type casting. In the following sections of this chapter, we will explore these concepts.

Also, in previous chapters, we saw that we can use Swift inference that infers the types unless we want to specify the type explicitly. We annotate the type in case we need to specify the type explicitly.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset