Swift 4.2 strange behavior

The code above sometimes makss playgrounds crash

If you have a way of reliably causing that to happen, please file an bug report at bugs.swift.org if you haven’t already!

If it doesn’t crash it fails with the following error:

So there’s problem: You expected that pattern syntax would let you write type annotations in the pattern. Which is a really natural assumption. After all

let x : Int = 3
let y : Double = 1
let xy = (x, y)

Really seems like it should “collapse” to

let (x: Int, y: Double) = (3, 1)

Bur let’s consider more meaningful names here

let (firstLabel: val1, secondLabel: val2) = (3, 1)

Now it’s clear what happened here (I hope): the syntax for declaring the elements of a tuple pattern with labels looks suspiciously like the syntax for declaring a plain old typed variable pattern, but “splatted” over each tuple element. You actually meant to do this:

let xy : (x: Int, y: Double) = (3, 1)

The reason the original goes through leads us to the next question:

Is this a bug in Swift?

Depends on your perspective. In my opinion, it’s certainly really really undesirable behavior to be able to shadow types like this. It even works outside of tuple patterns

func foo() -> Int {
  let Int = 1
  let Double = 3
  return Int + Double
}

Banning this would definitely be source breaking. My larger fear is that it would be massively so.

2 Likes