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


Swift StringInterpolationProtocol用法及代码示例

协议

StringInterpolationProtocol

在构建时用插值表示字符串文字的内容。

声明

protocol StringInterpolationProtocol

概述

每个 ExpressibleByStringInterpolation 类型都有一个关联的 StringInterpolation 类型,它符合 StringInterpolationProtocol 。 Swift 将 "The time is \(time)." as MyString 之类的表达式转换为一系列类似于以下内容的语句:


var interpolation = MyString.StringInterpolation(literalCapacity: 13, 
                                                 interpolationCount: 1)


interpolation.appendLiteral("The time is ")
interpolation.appendInterpolation(time)
interpolation.appendLiteral(".")


MyString(stringInterpolation: interpolation)

StringInterpolation 类型负责收集传递给其appendLiteral(_:)appendInterpolation 方法的段并将它们组装成一个整体,并根据需要进行转换。附加所有段后,插值将传递给正在创建的类型的 init(stringInterpolation:) 初始化程序,该初始化程序必须从 StringInterpolation 中提取累积的数据。

在简单的情况下,您可以使用 DefaultStringInterpolation 作为符合 ExpressibleByStringLiteral 协议的类型的插值类型。要使用默认插值,请将类型符合 ExpressibleByStringInterpolation 并实现 init(stringLiteral: String) 。插值中的值被转换为字符串,然后像任何其他字符串文字一样传递给该初始化程序。

处理字符串插值

使用自定义插值类型,每个插值段都被转换为对特殊 appendInterpolation 方法的调用。插值括号的内容被视为调用的参数列表。该参数列表可以包含多个参数和参数标签。

以下示例显示如何将字符串插值转换为对 appendInterpolation 的调用:

  • \(x) 转换为 appendInterpolation(x)

  • \(x, y) 转换为 appendInterpolation(x, y)

  • \(foo: x) 转换为 appendInterpolation(foo: x)

  • \(x, foo: y) 转换为 appendInterpolation(x, foo: y)

自定义类型中的 appendInterpolation 方法必须是返回 Void 的变异实例方法。此代码显示了自定义插值类型的 appendInterpolation 方法声明,该方法为用户输入提供特殊验证:


extension MyString.StringInterpolation {
    mutating func appendInterpolation(validating input: String) {
        // Perform validation of `input` and store for later use
    }
}

要使用此插值方法,请使用 validating 参数标签创建带有插值的字符串文字。


let userInput = readLine() ?? ""
let myString = "The user typed '\(validating: userInput)'." as MyString

appendInterpolation 方法几乎支持方法的所有特性:它们可以有任意数量的参数,可以为它们的任何或所有参数指定标签,可以提供默认值,可以有可变参数,并且可以有泛型类型的参数。最重要的是,它们可以被重载,因此符合StringInterpolationProtocol 的类型可以提供几种具有不同行为的不同appendInterpolation 方法。 appendInterpolation 方法也可以抛出;当用户使用这些插值之一编写文字时,他们必须使用 try 或其变体之一标记字符串文字。

可用版本

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

相关用法


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