Related types in Swift

What are the related types in a fast programming language? What are they used for?

According to the quick book of programming language:

When defining a protocol, it is sometimes useful to declare one or more related types as part of a protocol definition. the associated type gives the placeholder name (or alias) for the type that is used as part of the protocol. The actual type used for this bound type is not indicated until the protocol is accepted. Associated types are specified with the typealias keyword.

This text is not very clear to me. This will help a lot if you can explain the related types with an example.

Also, why is it useful to declare a bound type as part of a protocol definition?

+4
source share
1 answer

You have a protocol that defines methods and possibly properties that an implementation type should provide. Some of these methods / properties use or return objects of a different type to a type that implements the protocol. So, for example, if you have a protocol that defines certain types of collections of objects, you can define a related type that defines the elements of a collection.

So, let's say I want the protocol to define Stack, but what kind of stack? It doesn't matter, I just use the associated type to act as the owner of the place.

protocol Stack
{
    // typealias Element - Swift 1
    associatedtype Element // Swift 2+
    func push(x: Element)
    func pop() -> Element?
}

In the above Elementthere is a type of any objects in the stack. When I implement a stack, I use typealiasto indicate the specific type of stack elements.

class StackOfInt: Stack
{
    typealias Element = Int // Not strictly necessary, can be inferred
    var ints: [Int] = []

    func push(x: Int)
    {
        ints.append(x)
    }

    func pop() -> Int?
    {
        var ret: Int?
        if ints.count > 0
        {
            ret = ints.last
            ints.removeLast()
        }
        return ret
    }
}

, , Stack, , Element Int. , , typealias, Element . push() Element == Int.

+7

Source: https://habr.com/ru/post/1626377/


All Articles