当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Swift DefaultStringInterpolation用法及代码示例


结构

DefaultStringInterpolation

在构建时表示带有插值的字符串文字。

声明

@frozen struct DefaultStringInterpolation

概述

不要直接创建此类型的实例。当您使用字符串插值创建字符串时,编译器会使用它。相反,使用字符串插值来创建一个新字符串,方法是在括号中包含值、文字、变量或表达式,并以反斜杠 (\( ... ) ) 为前缀。


let price = 2
let number = 3
let message = """
              If one cookie costs \(price) dollars, \
              \(number) cookies cost \(price * number) dollars.
              """
print(message)
// Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars."

当实现 ExpressibleByStringInterpolation 一致性时,将 StringInterpolation 关联类型设置为 DefaultStringInterpolation 以获得与 Swift 内置的 String 类型相同的插值行为,并使用结果构造 String。如果您不想要默认行为或不想构造 String ,请改用符合 StringInterpolationProtocol 的自定义类型。

扩展默认字符串插值行为

标准库之外的代码可以通过扩展DefaultStringInterpolation 并添加appendInterpolation(...) 方法来扩展String 和许多其他常见类型的字符串插值。例如:


extension DefaultStringInterpolation {
    fileprivate mutating func appendInterpolation(
             escaped value: String, asASCII forceASCII: Bool = false) {
        for char in value.unicodeScalars {
            appendInterpolation(char.escaped(asASCII: forceASCII))
        }
    }
}


print("Escaped string: \(escaped: string)")

有关appendInterpolation 方法的详细信息,请参阅StringInterpolationProtocol

DefaultStringInterpolation 扩展应仅添加 mutating 成员,不应复制 self 或在转义闭包中捕获它。

可用版本

iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+

相关用法


注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 DefaultStringInterpolation。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。