When i try to enumerate array that contains enum values and find the index of some one with single if, swiftlint shows me for_where violation with single if warning. Probably for this situation there should be no warning?
import Foundation
enum Value {
case valueA, valueB
}
func firstIndexOfValueB(in array: [Value]) -> Int? {
for (index, value) in array.enumerated() { // `for_where` with single `if` warning here
if case .valueB = value {
return index
}
}
return nil
}
print(firstIndexOfValueB(in: [.valueA, .valueA, .valueB]) ?? -1)
In your case you could just use where value == .valueB, but I agree that the rule shouldn't warn if it's a pattern match if.
Hi.
In your case you could just use
where value == .valueB
Sure, this works fine for this case. But when we add some associated value like .valueB(number: Int) we cannot just type where value == .valueB for free - we should implement Equatable protocol. So, hope this will be fixed :)
Agree, this is a bug, but the sample shared in the first comment isn't why. Here's a sample that can't be changed to using a for where clause:
enum Value {
case valueA, valueB(a: Int)
}
func firstIndexOfValueB(in array: [Value]) -> Int? {
for (index, value) in array.enumerated() { // `for_where` with single `if` warning here
if case .valueB(_) = value {
return index
}
}
return nil
}
I think this change was not necessary and should be undone. This is not a bug as the example can be changed to:
enum Value {
case valueA, valueB(a: Int)
}
func firstIndexOfValueB(in array: [Value]) -> Int? {
for case let (index, .valueB) in array.enumerated() {
return index
}
return nil
}
Pattern matching also works in for loops.
Most helpful comment
I think this change was not necessary and should be undone. This is not a bug as the example can be changed to:
Pattern matching also works in for loops.