I'd like to see some type narrowing of some kind added to Swift (Typescript's implementation is pretty good).
I haven't been using Swift for a very long yet (only a few months of regular usage). Still, I've already noticed the boilerplate introduced by the lack of type narrowing in this short period, with Optional<Type>
especially.
let myString: String? = ""
// Here, you have to assert that the variable is not nil every time it's used,
// even though the compiler should be able to pick it up from context.
if myString != nil {
print(myString.reversed())
}
// Here, you have to either come up with a new name (naming is hard),
// or you have to shadow the variable, meaning you lose access to the original value.
if let mySafeString = myString {
print(mySafeString.reversed())
}
protocol Animal {
var name: String { get }
}
struct Cat: Animal {
var name: String
func meow() {}
}
struct Dog: Animal {
var name: String
func bark() {}
}
let myDog: Animal = Dog(name: "Bob")
if myDog is Dog {
// This is an example of where the boilerplate starts to add up.
(myDog as! Dog).bark()
}
There is also the potential for foot-guns with the first approach if, for example, someone copies some not-nil asserted code from within the != nil
check and pastes it somewhere that doesn't have the check around it. This situation is very possible, especially given how easy the !
can be to miss if you aren't looking for it.
let myString: String?
if myString != nil {
print(myString!.reversed())
}
// This could be an issue
print(myString!.reversed())
In an ideal world where type narrowing exists, we would be able to do this:
if myDog is Dog {
// The compiler keeps track of what we've already narrowed the type down to,
// so we don't need to assert its type - in this block, `myDog is Dog` will always be true.
myDog.bark()
}
Sorry that I can't go into the specifics of how this might be implemented - I'm not too well versed in how compilers work under the hood, but even if it's technically challenging to implement, I feel like this would make life life so much easier for developers and make the language much more intuitive to use.