swift--字符串之自定义字面量

2020-12-07  本文已影响0人  i诺离

什么是字面量

字面量意思是用"blah"近乎等价交换String("blah"),但这两者是不同的
""是字符串字面量表示

协议

字符串以字面量初始化遵循的协议
ExpressibleByStringLiteral

扩展字位族或者Unicode标量的以字面量形式进行初始化的协议
ExpressibleByExtendedGraphemeClusterLiteral
ExpressibleByUnicodeScalarLiteral

代码

struct SafeHTML {
    private(set) var value: String
    
    init(unsafe html: String) {
        self.value = html
    }
}

extension SafeHTML: ExpressibleByStringLiteral {
// 字面量初始化方法
    init(stringLiteral value: StringLiteralType) {
        self.value = value
    }
}

作用

使用字面量初始化时,默认处理字符串格式,安全便捷

extension String {
    var htmlEscaped: String {
        return replacingOccurrences(of: "<", with: "&lt;").replacingOccurrences(of: ">", with: "&gt;")
    }
}

extension SafeHTML: ExpressibleByStringLiteral {
// 字面量初始化方法
    init(stringLiteral value: StringLiteralType) {
        self.value = value. htmlEscaped
    }
}

let html: SafeHTML = "<p>html string</p>"

字面量中的插值

let pin = "pin"
let html: SafeHTML = "<p>html string\(pin) ddd \(raw: pin)</p>"

协议

继承自ExpressibleByStringLiteral
ExpressibleByStringInterpolation

初始化、appendLiteral、appendInterpolation
StringInterpolationProtocol

代码

extension SafeHTML: ExpressibleByStringInterpolation {
    init(stringInterpolation: SafeHTML) {
        print("stringInterpolation")
        self.value = stringInterpolation.value
    }

}

extension SafeHTML: StringInterpolationProtocol {
    init(literalCapacity: Int, interpolationCount: Int) {
        print("literalCapacity")
        self.value  = "起始拼接"
    }
    
    mutating func appendLiteral(_ literal: StringLiteralType) {
        //插值前字面量
        print("appendLiteral-\(literal)")
        value += literal
    }
    
    mutating func appendInterpolation<T>(_ x: T) {
        // 拼接参数
        print("appendInterpolation")
        self.value += String(describing: x).htmlEscaped
        print(self.value)
    }

    // 拓展插值的其他处理
    mutating func appendInterpolation<T>(raw x: T) {
        print("appendInterpolation")
        self.value += String(describing: x)
        print(self.value)
    }
}

上一篇 下一篇

猜你喜欢

热点阅读