文字列補間 (string interpolation) は、文字列リテラル内に値を含め、定数や変数、リテラル、式を組み合わせて新しい String
値を構築する手段です。文字列リテラルに挿入する各項目を丸括弧で囲み、バックスラッシュを前に置きます。
let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
// message は "3 times 2.5 is 7.5"
この例では、multiplier
の値が \(multiplier)
として文字列リテラルに挿入されています。文字列補間が評価される時に、プレースホルダは multiplier
の実際の値で置き換えられます。
multiplier
の値は、文字列内にある別の式の一部でもあります。この式は Double(multiplier) * 2.5
の値を算出し、結果 (7.5
) を文字列に挿入します。このケースでは、文字列リテラル内で \(Double(multiplier) * 2.5)
と記述されています。
NOTE
補間文字列の丸括弧内には、エスケープしていないバックスラッシュ (
\
) やキャリッジリターン、ラインフィードを含めることはできません。ですが、他の文字列リテラルを含めることは可能です。
Portions of this page are translations based on work created and shared by Apple and used according to terms described in the Creative Commons Attribution 4.0 International License.