SwiftFormat icon indicating copy to clipboard operation
SwiftFormat copied to clipboard

Put guard on its own line for multiline guard statements

Open Cyberbeni opened this issue 5 years ago • 4 comments

When the guard condition is multiple lines, I like having the else in a new line, like this:

guard let keyboardAnimationCurve = (dictionary[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber).flatMap({ UIView.AnimationCurve(rawValue: $0.intValue) }),
    let keyboardAnimationDuration = dictionary[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber,
    let keyboardFrameBegin = dictionary[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue,
    let keyboardFrameEnd = dictionary[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue
else {
    throw NotificationDecodingError(type: type(of: self), source: dictionary)
}

I think it would be cool to have an option to automatically place else in a new line when the condition is multiple lines, so that the body is separated from the condition instead of continuously having the same indentation.

Cyberbeni avatar Jan 23 '20 20:01 Cyberbeni

Maybe even like this? Where the first conditional statement is on a newline.

guard 
    let keyboardAnimationCurve = (dictionary[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber).flatMap({ UIView.AnimationCurve(rawValue: $0.intValue) }),
    let keyboardAnimationDuration = dictionary[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber,
    let keyboardFrameBegin = dictionary[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue,
    let keyboardFrameEnd = dictionary[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue
else {
    throw NotificationDecodingError(type: type(of: self), source: dictionary)
}

gregcotten avatar Feb 08 '20 18:02 gregcotten

@nicklockwood I like @gregcotten's suggestion. I can't promise anything but maybe I can find some time to add a rule for this - if it is something you would find useful as well. Let us know what you think!

ghost avatar May 11 '20 13:05 ghost

@daniel-mohemian I'd be happy to add this. Needs some discussion around the best way to configure it though.

There's already the (slightly confusingly-named) elseOnSameLine rule which moves else, catch or while statements to the same line as the previous closing }, so I'm wondering if this should be an extension of that rule, or a new one, etc.

nicklockwood avatar May 11 '20 17:05 nicklockwood

@Cyberbeni this is implemented in 0.45.0.

@gregcotten your suggested extension is not yet implemented, so I'll leave this open for now.

nicklockwood avatar Jul 30 '20 22:07 nicklockwood