Collection downcasts in cast patterns are now supported
About 2 min
Collection downcasts in cast patterns are now supported 관련
HACKING WITH SWIFT
What's new in Swift?
Collection downcasts in cast patterns are now supported | Changes in Swift 5.8
Collection downcasts in cast patterns are now supported
Available from Swift 5.8
This resolves another small but potentially annoying inconsistency in Swift where downcasting a collection – e.g. casting an array of ClassA
to an array of another type that inherits from ClassA
– would not be allowed in some circumstances.
For example, this code is now valid in Swift 5.8, whereas it would not have worked previously:
class Pet { }
class Dog: Pet {
func bark() { print("Woof!") }
}
func bark(using pets: [Pet]) {
switch pets {
case let pets as [Dog]:
for pet in pets {
pet.bark()
}
default:
print("No barking today.")
}
}
Before Swift 5.8 that would have led to the error message, “Collection downcast in cast pattern is not implemented; use an explicit downcast to '[Dog]' instead.” In practice, syntax such as if let dogs = pets as? [Dog] {
worked just fine, so I would imagine that error was rarely seen. However, this change does mean another language inconsistency is resolved, which is always welcome.
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
Opening existential arguments to optional parameters | Changes in Swift 5.8
Opening existential arguments to optional parameters