False positive for swift:S1854 Unused assignments should be removed

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

1 Like

Do you need further input / infos from our side ?

hello @Rebse ,

thanks for reporting this issue, I created ticket to fix it [SONARSWIFT-518] - Jira

hello @Rebse,

just a note, that your second issue is different problem already described here False positive code smell in swift, and we have another ticket for it [SONARSWIFT-517] - Jira