블로그

[Swift] 공식문서 Self.Element 분석

게시 2분

func map<T>(_ transform: (Self.Element) throws -> T) rethrows -> [T]

Array의 map 함수명에서 Self.Element가 어떤 의미인지 궁금해서 보니
Array이름은 다음과 같았다

public struct Array<Element>

분명 Element는 타입 매개변수인데 어떻게, 왜 공식문서에서는 Self.Element로 접근하는지 궁금해서 알아보니
map 함수는 Sequence 프로토콜에 extension을 통해서 map 함수를 구현해주고 있었다.

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) } }

잘 보니 공식문서의 Element는 타입 매개변수를 associatedtype으로 한번더 받아오고 있었다.
즉 Self로 Sequence의 타입이고 associatedtype인 Element를 얻어온것이어서 가능한거였다.

댓글

댓글을 남기면 닉네임(또는 GitHub 계정 정보)이 저장됩니다. 개인정보처리방침

GitHub