[#1525] Fix issue where removing return from failable init would break build

This commit is contained in:
Cal Stephens
2023-09-28 07:21:19 +01:00
committed by Nick Lockwood
parent 13e00c4de0
commit d6d29b0dcd
2 changed files with 42 additions and 0 deletions
+9
View File
@@ -3180,6 +3180,15 @@ public struct _FormatRules {
return
}
// Make sure we aren't in a failable `init?`, where explicit return is required
if let lastSignificantKeywordIndex = formatter.indexOfLastSignificantKeyword(at: startOfScopeIndex),
formatter.tokens[lastSignificantKeywordIndex] == .keyword("init"),
let nextToken = formatter.next(.nonSpaceOrCommentOrLinebreak, after: lastSignificantKeywordIndex),
nextToken == .operator("?", .postfix)
{
return
}
// Removes return statements in the given single-statement scope
func removeReturn(atStartOfScope startOfScopeIndex: Int) {
// If this scope is a single-statement if or switch statement then we have to recursively
+33
View File
@@ -2220,6 +2220,39 @@ class RedundancyTests: RulesTests {
testFormatting(for: input, rule: FormatRules.redundantReturn)
}
func testNoRemoveReturnInFailableInitWithConditional() {
let input = """
init?(optionalHex: String?) {
if let optionalHex {
self.init(hex: optionalHex)
} else {
return nil
}
}
"""
let options = FormatOptions(swiftVersion: "5.9")
testFormatting(for: input, rule: FormatRules.redundantReturn, options: options)
}
func testNoRemoveReturnInFailableInitWithNestedConditional() {
let input = """
init?(optionalHex: String?) {
if let optionalHex {
self.init(hex: optionalHex)
} else {
switch foo {
case .foo:
self.init()
case .bar:
return nil
}
}
}
"""
let options = FormatOptions(swiftVersion: "5.9")
testFormatting(for: input, rule: FormatRules.redundantReturn, options: options)
}
func testRemoveReturnInFailableInit() {
let input = "init?() { return nil }"
let output = "init?() { nil }"