Created
October 20, 2021 21:07
-
-
Save AnthonyMDev/08101004927a0e132f47875e36199121 to your computer and use it in GitHub Desktop.
String Interpolation Auto-Nesting Indentation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
public extension DefaultStringInterpolation { | |
/// A String interpolation function that respects nested indentation. | |
/// | |
/// Example: | |
/// ```swift | |
/// class Root { | |
/// let children: [Root] = [] | |
/// func description: String { | |
/// var desc = "\(type(of: self)) {" | |
/// children.forEach { child in | |
/// desc += "\n \(indented: child.debugDescription)," | |
/// } | |
/// if !children.isEmpty { desc += "\n" } | |
/// desc += "\(indented: "}")" | |
/// return desc | |
/// } | |
/// // Given classes A - E as subclasses of Root | |
/// | |
/// let root = Root(children: [A(children: [B(), C(children: [D()])]), E()]) | |
/// print(root.description) | |
/// ``` | |
/// This prints: | |
/// Root { | |
/// A { | |
/// B {} | |
/// C { | |
/// D {} | |
/// } | |
/// } | |
/// E {} | |
/// } | |
mutating func appendInterpolation(indented string: String) { | |
let indent = String(stringInterpolation: self).reversed().prefix { " \t".contains($0) } | |
if indent.isEmpty { | |
appendInterpolation(string) | |
} else { | |
appendLiteral(string.split(separator: "\n", omittingEmptySubsequences: false).joined(separator: "\n" + indent)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment