Hi,
using Sonarqube Enterprise 9.5.0 with Swift Code Quality and Security 4.6.0.5406
we’ve encountered two false positives for swift:S1854
Two reproducers
//
// DoCatchBug.swift
// SonarBugs
//
// Created by Johannes Bosecker on 02.08.22.
//
import Foundation
class DoCatchBug {
var ipsum: String?
func produceBug() {
do {
guard let data = "[\"foo\"]".data(using: .utf8) else {
return
}
let lorem = try JSONDecoder().decode([String].self, from: data)
guard let ipsum = ipsum else {
return
}
print(lorem.joined(separator: ", ") + ipsum)
self.ipsum = nil
} catch {
// Sonar creates a "code smell" here:
// Remove this useless assignment to local variable "ipsum"
ipsum = nil
}
}
}
DoCatchBug:
Accessing “ipsum” in the catch block is in the scope of the instance and not of the catch block. Therefore the code smell is incorrect.
//
// GuardBug.swift
// SonarBugs
//
// Created by Johannes Bosecker on 02.08.22.
//
import Foundation
class GuardBug {
let ipsum: String
init?() {
var lorem: String?
let foo: String? = "foo"
let bar: String? = "bar"
if let foo = foo, let bar = bar {
lorem = foo + " " + bar
}
// Sonar creates a "code smell" here:
// Remove this useless assignment to local variable "lorem"
guard let lorem = lorem else {
return nil
}
ipsum = lorem
}
}
GuardBug:
“lorem” is used after the guard statement. Therefore the code smell is just as wrong as in DoCatchBug
Gilbert