There have been several discussions in the past about this feature:
November 2016:
To avoid hijacking the guard let x = x thread entirely I've decided to try to write up a proposal on type narrowing in Swift.
Please give your feedback on the functionality proposed, as well as the clarity of the proposal/examples themselves; I've tried to keep it straightforward, but I do tend towards being overly verbose, I've always tried to have the examples build upon one another to show how it all stacks up.
Type Narrowing
Proposal: SE-NNNN <https://github.com/Haravikk/swift-evolution/b…
October 2020:
Kotlin implicitly casts an object after its type is checked. As a Swift and Kotlin programmer, I frequently find myself wishing Swift, which has a similar type system, had this feature. It seems to be in line with Swift's design goals of supporting sophisticated (while still being predictable) type inferencing.
These implicit casts are type-safe, reduce code clutter and improve performance by eliminating redundant checks:
Example (Swift-ified version):
if obj is String { print(obj.count) } /…
September 2022:
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 …
Notably, in the Nov 2016 thread, Chris Lattner wrote:
This is just MHO, but while I have been in favor of this in the (distant) past, I became convinced that this would be a bad idea when it comes to code maintenance over the long term. With our current (intentional shadowing based) design, you can always jump to the definition of a value to see where it was defined, and definitions always specify a type. Introducing flow senstitive type refinement breaks this model because the type of a decl depends not just on its declaration, but on a potentially arbitrary number of imperative checks that occur between the declaration and the use. This can make it much more difficult to understand code.
There were also questions about how it would interact with overload selection, how it would work with stored class properties (that might get changed while your code is running), and how it would work with computed variables.
Personally, I’ve never really wanted a feature like this. if let
works fine for me. I’ve never used a language with this feature before, though, so maybe I just don’t know the benefits.
3 Likes