Skip to content

Instantly share code, notes, and snippets.

@elfenlaid
Created May 21, 2021 07:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elfenlaid/568168ea4b2068aee2305752443a366f to your computer and use it in GitHub Desktop.
Save elfenlaid/568168ea4b2068aee2305752443a366f to your computer and use it in GitHub Desktop.
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