當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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