nicklockwood / SwiftFormat

A command-line tool and Xcode Extension for formatting Swift code
MIT License
7.77k stars 629 forks source link

conditionalAssignment matches expression within try block #1536

Closed antiraum closed 10 months ago

antiraum commented 10 months ago

Version 0.52.6 / Swift 5.9

conditionalAssignment reformats the following code

        let user2: User? = try {
            if let data2 = defaults.data(forKey: defaultsKey) {
                return try PropertyListDecoder().decode(User.self, from: data2)
            } else {
                return nil
            }
        }()

to

        let user2: User? = try if let data2 = defaults.data(forKey: defaultsKey) {
            try PropertyListDecoder().decode(User.self, from: data2)
        } else {
            nil
        }

Which doesn't seem to be allowed. The Xcode error message is

'try' may not be used on 'if' expression

nicklockwood commented 10 months ago

Paging @calda

nicklockwood commented 10 months ago

@calda do you think it's sufficient to remove the stray try here (and maybe do the same for await?) or would it be safer just to not remove the closure at all in this scenario?

nicklockwood commented 10 months ago

@antiraum FYI I think it's actually the redundantClosure rule that's a fault here.

calda commented 10 months ago

Ah, yes, this looks like a bug in redundantClosure. We'd need to either drop the proceeding try before the closure call if present.

calda commented 10 months ago

I did confirm both of these compile:

struct MyType {
  static func throwing() throws -> MyType { MyType() }
}

var condition = true

let value1: MyType? = try if condition {
  MyType.throwing()
} else {
  nil
}

let value2: MyType? = if condition {
  try MyType.throwing()
} else {
  nil
}

print(value1)
print(value2)

The problem is just when you have try in both places.

calda commented 10 months ago

I'll post a fix.

nicklockwood commented 10 months ago

@calda cool, thanks for confirming - I'll take care of it.

calda commented 10 months ago

Oh, sure, if you're planning on making the fix that's fine too. Thanks!

nicklockwood commented 10 months ago

@calda fix here: https://github.com/nicklockwood/SwiftFormat/commit/438243639ce6c5737bd3c10c0a1b9a98fc3a7830

nicklockwood commented 10 months ago

@antiraum fixed in 0.52.7

antiraum commented 10 months ago

Thanks a lot!