Vergiliy
Vergiliy

Reputation: 1356

Strange behavior switch-case statement in Swift

Usually the switch-case statement works like this: if the condition exactly matches the value, then the corresponding code block is executed. But in my case, something went wrong! Why does the code for "update" work for me while the condition is "date" !? I tried to recreate the situation in the playground - everything works correctly there. What is the problem?

Why does the update block work when key = "date"? Theoretically, the default block should work!?

My code:

print("Dictionary = \(dictionary)")

for (key, value) in dictionary {
    switch key {
    case BaseDatabase.COLUMN_ID:
        // My code
    case WeddingDatabase.COLUMN_PREMIUM:
        // My code
    case BaseDatabase.COLUMN_UPDATE_CLEAN:
        print("type = \(BaseDatabase.COLUMN_UPDATE_CLEAN), key = \(key)")
        // My code
    default:
        // My default code
    }
}

My console:

dictionary = ["note": <null>, "date": 2024-08-08 00:00:00, "update": 2019-07-09 08:57:05, "id_wedding": 1]

type = update, key = date // WHY??
type = update, key = update 

UPDATE:

Cut the code to the banal:

let key = "date"
switch key {
    case "update":
        print("key = \(key)")
    break
    default:
        print("default = \(key)")
    break
}  

Added code in viewDidLoad empty viewController. The console still displays key = date. I see the problem ONLY in my project. I tried to add code in a new project and in playgroud - everything works fine (default = date is output to the console). How can this be? I tried different Simulators (and iOS versions) - the problem is still there. I also tried to clean the project - the problem persists. Maybe somewhere in the project the work of switch statement is redefined - is this possible?

Upvotes: 1

Views: 450

Answers (1)

Vergiliy
Vergiliy

Reputation: 1356

I found a problem. In the String class extension, the ~= operator was redefined as follows:

extension String {
    static func ~= (lhs: String, rhs: String) -> Bool {
        return NSRegularExpression(rhs).matches(lhs)
    }
}

As it turned out, the ~= operator is used in a switch statement. To correct the error, I replaced this extension with the following:

extension String {
    func matches(pattern: String) -> Bool {
        return NSRegularExpression(pattern).matches(self)
    }
}

How I use it:

if value.matches(pattern: "#[0-9]{1,2}[A-Z]#" {
    // Code
}

It should be very attentive when redefining operators!

Upvotes: 2

Related Questions