結構
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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。