美文网首页
swift--字符串之自定义字面量

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

作者: i诺离 | 来源:发表于2020-12-07 16:17 被阅读0次

    什么是字面量

    字面量意思是用"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)
        }
    }
    
    

    相关文章

      网友评论

          本文标题:swift--字符串之自定义字面量

          本文链接:https://www.haomeiwen.com/subject/xphiwktx.html