Search code examples
iosswift3xcode8swiftlint

Cyclomatic Complexity Violation: Function should have complexity 10 or less: currently complexity equals 13 (cyclomatic_complexity)


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?

enter image description here


Solution

  • The warning occurs because your function is too complex as defined by the metric which essentially counts the number of decisions that need to be made.

    A simple way to avoid it in this particular case would be with some simple math:

    func selectedMenuInLoggedOutState(sender: UIButton) {
        guard let menu = LeftGuestMenu(rawValue: sender.tag - 1) else { return }
        self.changeGuestViewController(menu)
    }