自定义字符串插值实现安全日志脱敏
通过 ExpressibleByStringInterpolation 协议自动对敏感数据进行脱敏。 · 难度:入门 · +10XP
自定义字符串插值实现安全日志脱敏
当你需要在日志中输出用户信息但又不能暴露密码、身份证号时,普通的字符串插值很容易遗漏。本教程将展示如何创建一种安全的日志插值类型,让开发者使用 \(userID: .sensitive) 语法,在插值时刻自动调用脱敏函数,彻底避免明文泄露。同时你会学到如何扩展插值参数以支持多级脱敏策略。
struct SafeLog: ExpressibleByStringInterpolation {
let message: String
init(stringLiteral value: String) {
self.message = value
}
init(stringInterpolation: StringInterpolation) {
self.message = stringInterpolation.output
}
struct StringInterpolation: StringInterpolationProtocol {
var output = ""
mutating func appendLiteral(_ literal: String) { output.append(literal) }
mutating func appendInterpolation(masked value: CustomStringConvertible) {
let str = String(describing: value)
output.append(str.count > 4 ? String(str.prefix(2)) + "****" : "****")
}
}
}
let id = "123456789"
let log: SafeLog = "用户ID: \(masked: id)"