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") + } + } """) ]