func map<T>(_ transform: (Self.Element) throws -> T) rethrows -> [T]
I was curious what Self.Element means in the signature of Array's map function, and when I looked,
Array's name was as follows
public struct Array<Element>
Element is clearly a type parameter, so I was curious how and why the official docs access it as Self.Element, and when I looked into it,
the map function was implemented on the Sequence protocol through an extension.
https://github.com/apple/swift/blob/main/stdlib/public/core/Sequence.swift#L325
public protocol Sequence<Element> { /// A type representing the sequence's elements. associatedtype Element ... ... ... @inlinable public func map<T>( _ transform: (Element) throws -> T ) rethrows -> [T] { let initialCapacity = underestimatedCount var result = ContiguousArray<T>() result.reserveCapacity(initialCapacity) var iterator = self.makeIterator() // Add elements up to the initial capacity without checking for regrowth. for _ in 0..<initialCapacity { result.append(try transform(iterator.next()!)) } // Add remaining elements, if any. while let element = iterator.next() { result.append(try transform(element)) } return Array(result) } }
Looking closely, the Element in the official docs was receiving the type parameter once more as an associatedtype.
In other words, it worked because Self is the Sequence's type and it was getting Element, which is an associatedtype.