简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM