SwiftLint icon indicating copy to clipboard operation
SwiftLint copied to clipboard

Rule Request: Prefer `if` and `switch` expressions

Open SimplyDanny opened this issue 1 year ago • 2 comments

In version 5.9, Swift got support for if and switch expressions. A rule to enforce them where allowed should be possible.

In the first implementation, the rule does not need to be configurable. It should be opt-in and might support automatic rewriting.

Triggering:

func f(cond: Bool) -> Int {
    if cond {
        return 1
    } else {
        return 2
    }
}
func f(cond: Bool) {
    let r: Int
    if cond {
        r = 1
    } else {
        r = 2
    }
}

Non-triggering:

func f(cond: Bool) -> Int {
    if cond {
        // Nothing
    } else {
        return 2
    }
    return 1
}

SimplyDanny avatar Feb 23 '24 21:02 SimplyDanny

will work on this request

AballahNsour avatar May 17 '24 18:05 AballahNsour

I'd really like to see this, I've provided another example below which covers:

  • Where you are assigning to self
  • When you call a method that returns Never e.g. fatalError
  • When you throw an error
import Foundation

enum SupportedFruit {
  case lemon
  case lime
  case orange
}

enum SupportFruitError: Error {
  case didYouMean(String)
}

// NON-TRIGGERING
extension SupportedFruit {
  init(rawValue: String) throws {
    self = switch rawValue {
    case "🍋": .lemon
    case "🍋‍🟩": .lime
    case "🍊": throw SupportFruitError.didYouMean("to use an orange emoji instead of tangerine emoji")
    default: fatalError()
    }
  }
}

// TRIGGERING
extension SupportedFruit {
  init(rawValue: String) throws {
    switch rawValue {
    case "🍋": self = .lemon
    case "🍋‍🟩": self = .lime
    case "🍊": throw SupportFruitError.didYouMean("to use an orange emoji instead of tangerine emoji")
    default: fatalError()
    }
  }
}

@AballahNsour I see you have a branch on your fork for starting the implementation of this rule, let me know if I can do anything to help out. My Swift Syntax skills are pretty lacking though 😢.

Brett-Best avatar Jun 01 '24 03:06 Brett-Best