where clauses on contextually generic declarations
About 2 min
where clauses on contextually generic declarations 관련
HACKING WITH SWIFT
What's new in Swift?
where clauses on contextually generic declarations | Changes in Swift 5.3
where clauses on contextually generic declarations
Available from Swift 5.3
SE-0267 (apple/swift-evolution
) introduced the ability to attach a where
clause to functions inside generic types and extensions.
For example, we could start with a simple Stack
struct that let us push and pop values from a private array:
struct Stack<Element> {
private var array = [Element]()
mutating func push(_ obj: Element) {
array.append(obj)
}
mutating func pop() -> Element? {
array.popLast()
}
}
Using SE-0267, we could add a new sorted()
method to that stack, but only for times when the elements inside the stack conform to Comparable
:
extension Stack {
func sorted() -> [Element] where Element: Comparable {
array.sorted()
}
}
Other Changes in Swift 5.3
Multi-pattern catch clauses | Changes in Swift 5.3
Multi-pattern catch clauses
Multiple trailing closures | Changes in Swift 5.3
Multiple trailing closures
Synthesized Comparable conformance for enums | Changes in Swift 5.3
Synthesized Comparable conformance for enums
self is no longer required in many places | Changes in Swift 5.3
self is no longer required in many places
Type-based program entry points | Changes in Swift 5.3
Type-based program entry points
Enum cases as protocol witnesses | Changes in Swift 5.3
Enum cases as protocol witnesses
Refined didSet semantics | Changes in Swift 5.3
Refined didSet semantics
A new Float16 type | Changes in Swift 5.3
A new Float16 type
Swift Package Manager gains binary dependencies, resources, and more | Changes in Swift 5.3
Swift Package Manager gains binary dependencies, resources, and more