结构
Default
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+
相关用法
- Swift DefaultStringInterpolation description用法及代码示例
- Swift DefaultStringInterpolation appendInterpolation(_:)用法及代码示例
- Swift DefaultIndices endIndex用法及代码示例
- Swift DefaultIndices index(_:offsetBy:limitedBy:)用法及代码示例
- Swift DefaultIndices prefix(through:)用法及代码示例
- Swift DefaultIndices reduce(_:_:)用法及代码示例
- Swift DefaultIndices min(by:)用法及代码示例
- Swift DefaultIndices allSatisfy(_:)用法及代码示例
- Swift DefaultIndices shuffled()用法及代码示例
- Swift DefaultIndices shuffled(using:)用法及代码示例
- Swift DefaultIndices first用法及代码示例
- Swift DefaultIndices prefix(_:)用法及代码示例
- Swift DefaultIndices lexicographicallyPrecedes(_:)用法及代码示例
- Swift DefaultIndices index(_:offsetBy:)用法及代码示例
- Swift DefaultIndices compactMap(_:)用法及代码示例
- Swift DefaultIndices suffix(_:)用法及代码示例
- Swift DefaultIndices dropLast(_:)用法及代码示例
- Swift DefaultIndices last(where:)用法及代码示例
- Swift DefaultIndices filter(_:)用法及代码示例
- Swift DefaultIndices lastIndex(of:)用法及代码示例
- Swift DefaultIndices contains(_:)用法及代码示例
- Swift DefaultIndices max(by:)用法及代码示例
- Swift DefaultIndices prefix(upTo:)用法及代码示例
- Swift DefaultIndices split(separator:maxSplits:omittingEmptySubsequences:)用法及代码示例
- Swift DefaultIndices contains(where:)用法及代码示例
注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 DefaultStringInterpolation。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。