Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swiftlint warning : For Where Violation: `where` clauses are preferred over a single `if` inside a `for`. (for_where)

I am using swift for my application development and using Swift lint. But I am getting a warning regarding the following code:

for settingsKeys in searchResults {

        if  settingsKeys.key == settingsObject.key {
          settingsKeys.value = settingsObject.value
          try context.save()
        }
      }

The screenshot is attached hereby:

enter image description here

No automatic fix option is available, so how do I eliminate this warning?

like image 938
Chelsea Shawra Avatar asked Aug 09 '17 12:08

Chelsea Shawra


2 Answers

The syntax preferred by your swiftlint configuration is:

for settingsKeys in searchResults where settingsKeys.key == settingsObject.key {
    settingsKeys.value = settingsObject.value
    try context.save()
}

Which is the similar to

for settingsKeys in (searchResults.filter { $0.key == settingsObject.key }) {
    settingsKeys.value = settingsObject.value
    try context.save()
}

If you know there is only one result with the same key, you might directly use

if let settingsKeys = (searchResults.first { $0.key == settingsObject.key }) {
    settingsKeys.value = settingsObject.value
    try context.save()
}
like image 109
Sulthan Avatar answered Nov 16 '22 05:11

Sulthan


Looks like it's expecting the where to be part of the for

for settingsKeys in searchResults where settingsKeys.key == settingsObject.key {
    settingsKeys.value = settingsObject.value
    try context.save()
}
like image 34
Ashley Mills Avatar answered Nov 16 '22 04:11

Ashley Mills