I have the following code in swift3 and i am using swift lint for linting the code. The code is given as follows:
func selectedMenuInLoggedOutState(sender: UIButton) { switch sender.tag { case 1: if let menu = LeftGuestMenu(rawValue: 0) { self.changeGuestViewController(menu) } case 2: if let menu = LeftGuestMenu(rawValue: 1) { self.changeGuestViewController(menu) } case 3: if let menu = LeftGuestMenu(rawValue: 2) { self.changeGuestViewController(menu) } case 4: if let menu = LeftGuestMenu(rawValue: 3) { self.changeGuestViewController(menu) } case 5: if let menu = LeftGuestMenu(rawValue: 4) { self.changeGuestViewController(menu) } case 6: if let menu = LeftGuestMenu(rawValue: 5) { self.changeGuestViewController(menu) } default: break } }
The swift lint generates a "Cyclomatic Complexity Violation" warning. Why did this warning occur and how does one resolve it?
Some of them are extremely easy to address, even by autocorrect; however, some warnings may be harder to remove, for example “Cyclomatic Complexity Violation”. The idea of cyclomatic complexity is very simple: the more branching and jumping logic you have in your code, the more complex your code is.
Cyclomatic complexity is a measurement developed by Thomas McCabe to determine the stability and level of confidence in a program. It measures the number of linearly-independent paths through a program module.
Consequences: A high cyclomatic complexity for a particular function means that the function will be difficult to understand, and more difficult to test. That in turn means functions with a cyclomatic complexity above 10 or 15 can be reasonably expected to have more undetected defects than simpler functions.
Cyclomatic Complexity Measures The Cyclomatic complexity defines the number of independent paths in the basis set of the program that provides the upper bound for the number of tests that must be conducted to ensure that all the statements have been executed atleast once.
The method is too complex. But instead of rewriting the code, you could exclude switches
from the cyclomatic_complexity
calculation (since they are perfectly readable) like this:
cyclomatic_complexity: ignores_case_statements: true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With