52

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?

Tim Sylvester
  • 22,897
  • 2
  • 80
  • 94
Chelsea Shawra
  • 1,593
  • 4
  • 22
  • 43

2 Answers2

124

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()
}
Sulthan
  • 128,090
  • 22
  • 218
  • 270
4

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()
}
Ashley Mills
  • 50,474
  • 16
  • 129
  • 160