Opening existential arguments to optional parameters
About 2 min
Opening existential arguments to optional parameters êŽë š
HACKING WITH SWIFT
What's new in Swift?
Opening existential arguments to optional parameters | Changes in Swift 5.8
Opening existential arguments to optional parameters
Available from Swift 5.8
SE-0375 (apple/swift-evolution
) extends a Swift 5.7 feature that allowed us to call generic functions using a protocol, fixing a small but annoying inconsistency: Swift 5.7 would not allow this behavior with optionals, whereas Swift 5.8 does.
For example, this code worked great in Swift 5.7, because it uses a non-optional T
parameter:
func double<T: Numeric>(_ number: T) -> T {
number * 2
}
let first = 1
let second = 2.0
let third: Float = 3
let numbers: [any Numeric] = [first, second, third]
for number in numbers {
print(double(number))
}
In Swift 5.8, that same parameter can now be optional, like this:
func optionalDouble<T: Numeric>(_ number: T?) -> T {
let numberToDouble = number ?? 0
return numberToDouble * 2
}
for number in numbers {
print(optionalDouble(number))
}
In Swift 5.7 that would have issued the rather baffling error message âType 'any Numeric' cannot conform to 'Numericââ, so itâs good to see this inconsistency resolved.
Other Changes in Swift 5.8
Lift all limitations on variables in result builders | Changes in Swift 5.8
Lift all limitations on variables in result builders
Function back deployment | Changes in Swift 5.8
Function back deployment
Allow implicit self for weak self captures, after self is unwrapped | Changes in Swift 5.8
Allow implicit self for weak self captures, after self is unwrapped
Concise magic file names | Changes in Swift 5.8
Concise magic file names
Collection downcasts in cast patterns are now supported | Changes in Swift 5.8
Collection downcasts in cast patterns are now supported