Skip to content

Instantly share code, notes, and snippets.

@elfenlaid
Created May 21, 2021
Embed
What would you like to do?
Custom Swift String Interpolation: Logs Privacy
struct Message {
enum Privacy {
case `public`
case `private`
}
var value: String
}
extension Message: CustomStringConvertible {
var description: String { value }
}
extension Message: ExpressibleByStringLiteral {
init(stringLiteral value: StringLiteralType) {
self.init(value: value)
}
}
extension Message: ExpressibleByStringInterpolation {
init(stringInterpolation: StringInterpolation) {
self.init(value: stringInterpolation.string)
}
struct StringInterpolation: StringInterpolationProtocol {
var string = ""
init(literalCapacity: Int, interpolationCount: Int) {
string.reserveCapacity(literalCapacity)
}
mutating func appendLiteral(_ literal: String) {
string.append(literal)
}
mutating func appendInterpolation<T>(_ value: T, privacy: Privacy = .private) where T: CustomStringConvertible {
switch privacy {
case .public:
string.append(value.description)
case .private:
string.append(
Array(repeating: "*", count: value.description.count).joined()
)
}
}
}
}
func log(_ message: Message) {
print(message)
}
log("Hello, \("world!", privacy: .public)")
log("Hello, \("secret", privacy: .private)")
log("Static strings say whatever they want")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment