Swift - Remove the default case and replace it with a case in switch statement that matches any values

Introduction

You can remove the default case and replace it with a case that matches any values:

Demo

//(math, science)
var scores =  (30,20)
switch scores {//from   www .jav  a  2  s .c  om
    case  (0,0):
        print("This is not good!")
    case  (100,100):
        print("Perfect score!")
    case (50...100, let science):
        print("Math passed!")
        if science<50 {
            print("But Science failed!")
        } else {
            print("And Science passed too!")
        }
    case  (let math, 50...100):
        print("Science passed!")
        if math<50 {
            print("But Math failed!")
        } else {
            print("And Math passed too!")
        }
    case  (let math, let science)://replacing default
        print("Math is \(math) and Science is \(science)")
}

Result

Instead of writing the let keyword twice for both variables as

case (let math, let science):

you could rewrite it like this:

case let  (math, science):
print("Math is \(math) and Science is \(science)")

Related Topic