Created
May 21, 2021 07:46
-
-
Save elfenlaid/568168ea4b2068aee2305752443a366f to your computer and use it in GitHub Desktop.
Custom Swift String Interpolation: Logs Privacy
This file contains 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
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