Bilbo Baggins
Bilbo Baggins

Reputation: 3692

Swift: What does this statement in Extension mean?

Here is a swift protocol and extension to convert a range to an array:

protocol ArrayRepresentable {
    typealias ArrayType

    func toArray() -> [ArrayType]
}

extension Range : ArrayRepresentable {
    func toArray() -> [Element] {
        return [Element](self)
    }
}

I don't understand the meaning of the following line:

return [Element](self)

What does it return? How does it manage to append the element to an existing array?

Upvotes: 0

Views: 83

Answers (1)

Scott Thompson
Scott Thompson

Reputation: 23701

Basically it creates a new array with each of the elements in the range.

You could create an empty array of Ints, for example, using [Int]().

In this case Element is the type of the items "contained" in the Range. When it calls the arrays init it passes the range itself as a parameter and that initializer walks through the elements in the range and adds each to the array.

Upvotes: 1

Related Questions