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

Chelsea Shawra picture Chelsea Shawra · Aug 9, 2017 · Viewed 13.6k times · Source

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?

Answer

Sulthan picture Sulthan · Aug 9, 2017

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()
}