Generic types can work with any type. In this video, explore how to build a generic Box type.
- [Instructor] Generic types solve a similar problem as generic functions. Generic types can work with any type and not only with the particular class, structure, or enumeration. This is why Swift's built in collection types: the array, the set, and the dictionary are implemented as generic collections. Let's say that we need a wrapper that can hold values of various types. Strings, integers, dates, you name it. I'm going to switch to another playground page where we have some pre-defined structs.
With a non-generic approach, we'd end up having a wrapper for each type. You've got a StringWrapper for string types, an IntWrapper for integers, and a DateWrapper for dates. The number of dedicated wrapper types increases with each new type that we need to support. Besides, with every added type, we duplicate code. The code becomes a maintenance nightmare. Actually, even choosing the right wrapper type is challenging. Generics are here to help us.
I'm going to remove these structs. And let's start implementing our generic solution. We can define a wrapper structure that can work with any type. The place holder appears right after the type's name within angled bracket. This placeholder type can be then used anywhere within the type's definition. I'm going to use it for our storage property. I'm also going to add an initializer that takes an argument of placeholder type.
Let's call it "value of type T". This is going to initialize our internal storage property. Storage equals value. Using the generic version is straight forward. I'm going to create the constant. Let's call it "piWrapped". I provide a value, which is a double, and initialize it with the value "double.pi".
In most cases, we can even skip the place holder type. The compiler will be able to figure out the type based on the provided value. Now let's complete a new instance that wraps a string. StingWrapped equals wrapper. Again, I won't provide the type. We'll let the Swift's type influence engine figure out the type based on the value, which is a string. Or, we can even wrap a date, using our wrapper.
Let's call it "dateWrapped" equals wrapper. And provide a date instance. We can apply type constraints to generic types. For example, we could limit the wrapper type to values that adopt the equatable protocol. Now, the wrapper structure will be able to wrap only types that conform to the equatable protocol.
- Comparing object-oriented programming with protocol-oriented programming
- Methods and class-bound protocols
- Adopting a protocol
- Declaring asynchronous behavior
- Preparing and implementing fallback logic
- Implementing an app using protocol-oriented programming