Swiftlint: for_where with single if for enumed enumerated array

Created on 5 Dec 2017  路  4Comments  路  Source: realm/SwiftLint

New Issue Checklist

Bug Report

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)
bug

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:

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.

All 4 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

castus picture castus  路  3Comments

BalestraPatrick picture BalestraPatrick  路  3Comments

ArthurMaroulier picture ArthurMaroulier  路  3Comments

jcarroll-mediafly picture jcarroll-mediafly  路  3Comments

ivanbruel picture ivanbruel  路  3Comments