Swift 6.0 Protocol Extensions: Powerful New Tricks You Need to Know
Unleashing the Full Potential of Protocols with New Enhancements in Swift 6.0
medium.com
Swift 6.0에서 프로토콜 익스텐션의 추가된 기능들에 대해 설명해주고 있다
1. Parameterized Extensions
protocol Cacheable {
associatedtype Key
associatedtype Value
func retrieve(for key: Key) -> Value?
func save(value: Value, for key: Key)
}
extension Cacheable where Key == String, Value: Codable {
func saveToUserDefaults(value: Value, for key: Key) {
let data = try? JSONEncoder().encode(value)
UserDefaults.standard.set(data, forKey: key)
}
func retrieveFromUserDefaults(for key: Key) -> Value? {
guard let data = UserDefaults.standard.data(forKey: key) else { return nil }
return try? JSONDecoder().decode(Value.self, from: data)
}
}
이렇게 protocol의 extensions을 특정 타입 요구사항을 맞출 수 있게 해주는다는 건데 이건 원래 되지 않았나 싶다
2. Improved Static Dispatch for Extensions
class의 override methods들 처럼 extension으로 정의한 protocol도 dynamic dispatch를 사용한다. 하지만 실제로 해보면 class의 ovrride methods들도 간단한 것들은 static으로 작동하는데(최적화를 끄면 dynamic임을 확인 가능), Swift 6.0부터 protocol도 static dispatch들을 자주 사용한다고 한다. 즉 성능 향상
3. Defaults Implementations with Generic Constratints
protocol Printable {
func printDetails()
}
extension Printable where Self: CustomStringConvertible {
func printDetails() {
print("Description: \(self.description)")
}
}
struct Product: Printable, CustomStringConvertible {
let name: String
var description: String { return "Product: \(name)" }
}
let item = Product(name: "MacBook Air")
item.printDetails() // Automatically uses the default implementation.
프로토콜의 기본 구현을 모든 타입에게 적용하는게 아니라 특정 타입에게만 만족할 수 있게 변경. 좀 더 세밀하게 제어할 수 있다.
4. Extension-Level Attributes
@available(iOS 17, macOS 14, *)
extension Collection {
func firstThreeElements() -> [Element] {
return Array(self.prefix(3))
}
}
protocol extension 전체에 속성 적용 가능. 각각 메소드에 attributes를 붙이는게 아니라 전체에 적용할 수 있으므로 코드가 깔끔해짐
5. More Powerful Type Constraints in Extensions
protocol EquatableCollection: Collection where Element: Equatable {}
extension EquatableCollection {
func containsDuplicates() -> Bool {
return self.count != Set(self).count
}
}
struct NameList: EquatableCollection {
var elements: [String]
var startIndex: Int { elements.startIndex }
var endIndex: Int { elements.endIndex }
subscript(position: Int) -> String {
return elements[position]
}
func index(after i: Int) -> Int {
return elements.index(after: i)
}
}
let names = NameList(elements: ["Alice", "Bob", "Alice"])
print(names.containsDuplicates()) // true
타입 제약 조건을 좀더 상세하게 표현 가능. 위에 코드와 같이 Collection을 채택하면서 AssociatedType인 Element가 Equtable을 준수해야하는 제약을 추가했음.
타입 안전성을 보장하고 표현이 더 깔끔하게 가능한듯
흠.. 평소에 associatedType을 자주 안써서 그런지 막 와닫지는 않지만 알면 좋을것 같다.
추가로 Swift 6.0에 뭐가 추가되었는지 기억이 나지 않아 찾아보았다. 분명히 WWDC를 봤는데..
'공부 > medium' 카테고리의 다른 글
[Swift] Alamofire VS URLSession, Type Casting Performance (0) | 2025.03.26 |
---|---|
[SwiftUI] Why you Need AnyView? AnyView는 잘 쓰면 좋다 [요약/정리] (0) | 2025.03.26 |