Other Uses for Generics

In addition to creating functions with generic types, you can also provide your own custom types, using classes, structs, and enums. The array type is a good example of this. Notice that when you create an array, you are setting the type at creation time:

var a:[Int] = [1,2,3]

Notice that the preceding example tells the array to use Ints. Here’s another way to do this:

var a:Array<Int> = [1,2,3]

This syntax is the generic syntax for an array. It tells you that what appears after the equals sign is an array made of Ints. Inside those angled brackets you declare that the array uses Ints. An array is just a list or sequence. You can create your own array-like structure that has a similar implementation to the array but with ...

Get Learning Swift™ Programming now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.