ExpressibleByStringInterpolation
聲明
protocol ExpressibleByStringInterpolation : ExpressibleByStringLiteral
概述
使用字符串插值在字符串文字中包含一個或多個表達式,用一組括號括起來並以反斜杠為前綴。例如:
let price = 2
let number = 3
let message = "One cookie: $\(price), \(number) cookies: $\(price * number)."
print(message)
// Prints "One cookie: $2, 3 cookies: $6."
擴展默認插值行為
通過擴展 DefaultStringInterpolation
向現有類型添加新的插值行為,該類型為 String
和 Substring
等類型實現插值,以添加具有新行為的 appendInterpolation(_:)
重載。
有關詳細信息,請參閱 DefaultStringInterpolation
和 StringInterpolationProtocol
文檔。
創建支持默認字符串插值的類型
要創建一個支持字符串文字和插值但不需要任何自定義行為的新類型,請將類型符合 ExpressibleByStringInterpolation
並實現 ExpressibleByStringLiteral
協議聲明的 init(stringLiteral: String)
初始化程序。 Swift 會自動使用 DefaultStringInterpolation
作為插值類型,並為 init(stringInterpolation:)
提供一個實現,將插值後的文字內容傳遞給 init(stringLiteral:)
,因此您不需要實現任何特定於該協議的內容。
創建支持自定義字符串插值的類型
如果您想要一個一致的類型來區分字麵量和插值段,限製可以插值的類型,支持與 String
上的插值器不同的插值器,或者避免構造包含數據的 String
,該類型必須指定一個自定義StringInterpolation
關聯類型。此類型必須符合 StringInterpolationProtocol
並具有匹配的 StringLiteralType
。
有關詳細信息,請參閱 StringInterpolationProtocol
文檔。
可用版本
相關用法
- Swift ExpressibleByStringInterpolation init(stringInterpolation:)用法及代碼示例
- Swift ExpressibleByStringLiteral用法及代碼示例
- Swift ExpressibleByIntegerLiteral用法及代碼示例
- Swift ExpressibleByUnicodeScalarLiteral用法及代碼示例
- Swift ExpressibleByFloatLiteral init(floatLiteral:)用法及代碼示例
- Swift ExpressibleByIntegerLiteral init(integerLiteral:)用法及代碼示例
- Swift ExpressibleByExtendedGraphemeClusterLiteral用法及代碼示例
- Swift ExpressibleByFloatLiteral用法及代碼示例
- Swift ExpressibleByDictionaryLiteral用法及代碼示例
- Swift ExpressibleByBooleanLiteral init(booleanLiteral:)用法及代碼示例
- Swift ExpressibleByArrayLiteral用法及代碼示例
- Swift ExpressibleByArrayLiteral init(arrayLiteral:)用法及代碼示例
- Swift EnumeratedSequence forEach(_:)用法及代碼示例
- Swift EnumeratedSequence.Iterator map(_:)用法及代碼示例
- Swift EnumeratedSequence.Iterator flatMap(_:)用法及代碼示例
- Swift EmptyCollection first(where:)用法及代碼示例
- Swift EmptyCollection index(_:offsetBy:limitedBy:)用法及代碼示例
- Swift EnumeratedSequence drop(while:)用法及代碼示例
- Swift EmptyCollection partition(by:)用法及代碼示例
- Swift EnumeratedSequence.Iterator allSatisfy(_:)用法及代碼示例
- Swift EmptyCollection prefix(upTo:)用法及代碼示例
- Swift EmptyCollection starts(with:)用法及代碼示例
- Swift EnumeratedSequence用法及代碼示例
- Swift EmptyCollection.Iterator split(maxSplits:omittingEmptySubsequences:whereSeparator:)用法及代碼示例
- Swift EmptyCollection.Iterator starts(with:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 ExpressibleByStringInterpolation。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。