In Xcode, let's say I have an arbitrary section of code in a Swift file such as:
static func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
If I comment it out like this:
/*
static func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
*/
Then if I select all and re-indent the entire file using (^ + I on Mac), then it not only re-indents the "normal" surrounding, un-commented code, but it (perhaps understandably) re-indents the "code" inside the /* ... */ to look this this:
/*
static func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
*/
This may seem ok for a small section of code but sometimes I like to comment out entire files temporarily just to prevent "duplicate declaration of..." errors when experimenting with alternatives.... but I still want that commented code to be readable (indented as code) so it can be used for reference.
So, in Xcode, is there any way to prevent the re-indent command from effecting code inside comment blocks marked with /* ... */?
I don't think this is possible in Xcode but there are some workarounds. One is to use another formatter, I use SwiftFormat for my current project and when testing it for this situation I see that it does not re-format commented code in any way so that would work.
Another solution that is Xcode only but will require a few extra steps is to use line comments and code folding. Xcode will not re-format code that is commented out with // when using ctrl-I.
So what you can do is to fold the relevant code by clicking the code folding ribbon to the left of the code at an appropriate place and click the ribbon or use one of the commands under Editor -> Code Folding and then place the cursor at the start of the folded line and use comment selection, Editor -> Structure -> Comment Selection.
This might seem overly complicated but with the right use of keyboard shortcuts it should be easier and quicker