From 41280b336a3aaccb1048a7b05fcf5ee064c85957 Mon Sep 17 00:00:00 2001 From: Martin Redington Date: Fri, 23 Jun 2023 00:24:27 +0100 Subject: [PATCH] Fix for #5075 --- .../UnneededSynthesizedInitializerRule.swift | 10 +++++++++- ...ededSynthesizedInitializerRuleExamples.swift | 17 +++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/UnneededSynthesizedInitializerRule.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/UnneededSynthesizedInitializerRule.swift index 6690fdce35..ebffd154fb 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/UnneededSynthesizedInitializerRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/UnneededSynthesizedInitializerRule.swift @@ -120,7 +120,7 @@ private extension StructDeclSyntax { return initializers.filter { self.initializerParameters($0.parameterList, match: storedProperties) && - ($0.parameterList.isEmpty || initializerBody($0.body, matches: storedProperties)) && + (($0.parameterList.isEmpty && hasNoSideEffects($0.body)) || initializerBody($0.body, matches: storedProperties)) && initializerModifiers($0.modifiers, match: storedProperties) && !$0.isInlinable } } @@ -215,6 +215,14 @@ private extension StructDeclSyntax { return statements.isEmpty } + private func hasNoSideEffects(_ initializerBody: CodeBlockSyntax?) -> Bool { + guard let initializerBody else { + return true + } + return initializerBody.statements.isEmpty + } + + // Does the actual access level of an initializer match the access level of the synthesized // memberwise initializer? private func initializerModifiers( diff --git a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/UnneededSynthesizedInitializerRuleExamples.swift b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/UnneededSynthesizedInitializerRuleExamples.swift index 43fa952437..29f570b631 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Idiomatic/UnneededSynthesizedInitializerRuleExamples.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Idiomatic/UnneededSynthesizedInitializerRuleExamples.swift @@ -180,6 +180,23 @@ enum UnneededSynthesizedInitializerRuleExamples { self.bar = bar } } + """), + Example(""" + struct Foo { + init() { + print("perform side effect") + } + } + """), + Example(""" + struct Foo { + var bar: Int = 0 + + init(bar: Int = 0) { + self.bar = bar + print("perform side effect") + } + } """) ]