I have just watched WWDC22 What's new in Swift and found out it brings so much improvement on generics and protocols.
The video mentions we can pass any
type to some
type argument and Swift will handle that case for us, like:
extension Mailmap {
mutating func mergeEntriesfrom other: some Mailmap) { … }
}
func mergeMailmaps(_ a: any Mailmap, _ b: any Mailmap) -> any Mailmap {
var copy = a
copy.mergeEntries(from: b) // works fine
return a
}
That feature could be very useful and I can't wait to use it. I wrote some code to test that feature, turns out the behavior is more complicated than it looks like.
class StarFieldRunner {
func runSome(_ v: some StarField) {
}
func runAny(_ v: any StarField) {
// 1. Works fine
runSome(v)
// 2. Works fine
let v2 = v
runSome(v2)
// 3. Compile Error: Type 'any StarField' cannot conform to 'StarField'
var v3 = v
runSome(v3)
}
}
- If we pass the parameter of
any
type intosome
type directly, everything works fine. - If we pass a constant defined using the
any
type tosome
type, it works too. - If we pass a new variable defined from the
any
type tosome
type, the old error is raised again.
I have no idea if it's intended behavior or a language bug. Any information will be welcomed.