Swiftlint警告:对于Where Violation:`where`子句比`for`中的单个`if`更受欢迎。 (for_where)

时间:2017-08-09 12:19:37

标签: swift3 xcode8 swiftlint

我正在使用swift进行应用程序开发并使用swift lint。但我收到有关以下代码的警告:

for settingsKeys in searchResults {

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

屏幕截图如下:

enter image description here

2 个答案:

答案 0 :(得分:42)

swiftlint配置首选的语法是:

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

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

如果您知道只有一个结果具有相同的key,则可以直接使用

if let settingsKeys = (searchResults.first { $0.key == settingsObject.key }) {
    settingsKeys.value = settingsObject.value
    try context.save()
}

答案 1 :(得分:2)

看起来它期待where成为for的一部分......

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