0

I recently started learning Swift and came across a Swift switches, it seems that switches must be exhaustive in Swift, for example.

This will cause a compiler error

let nums = 1...5
for num in nums 
{
    switch num
    {
       case 2:
           // Do Something
       // Will throw a comilation error unless default: was added
    }
}

Whilst in C#, this is perfectly acceptable

var nums = new[] {1, 2, 3, 4, 5};
foreach (var num in nums)
{
    switch (num)
    {
        case 2:
            // Do Something
            break;
    }
}

Is this just a infrastructure preference or is there some other reason for this?

Mike
  • 826
  • 11
  • 31

1 Answers1

2

Swift has chosen to a few things differently than other languages, otherwise there would not be a need for a new language.

This is especially true for switch which has e.g. chosen to not fallthrough unless being told so explicitly. This allows it to omit the pervasive break from other C-like languages (which I consider an excellent choice btw. considering that I very rarely want my case to fall through).

It is also not unheard of to have languages require default for switches, e.g. for Java when switching on enums as in this question. In this case I would generally consider this a good thing, as I might otherwise forget to add a case in some random switch statement where I intended to cover all the values of an enum or range if the enum eventually gets an additional element. This way I have a way to express this (by not implementing a default clause) which I consider superior to not having this possibility (by simply assuming "nothing to be done" as in the case of C#).

Community
  • 1
  • 1
Patru
  • 4,481
  • 2
  • 32
  • 42
  • 3
    Just for completeness, C# does not allow "fallthrough" either. http://stackoverflow.com/questions/3047863/how-can-i-use-more-than-one-constant-for-a-switch-case-in-c/3049601#3049601 – Gjeltema Dec 01 '14 at 00:41
  • Thanks for this clarification. I do not know C# well enough to be able to make this distinction, but it is absolutely something to be pointed out. – Patru Dec 01 '14 at 01:03
  • I guess my question should have been why did Swift choose to not fallthrough or allow breaks – Mike Dec 01 '14 at 03:00