Інтерполяція рядків

Swift:
Інтерполяція рядків

How to: (Як це зробити:)

let name = "Олексій"
let age = 29
let greeting = "Привіт, мене звати \(name) і мені \(age) років."
print(greeting) // Виводить: Привіт, мене звати Олексій і мені 29 років.

With this, you can also do calculations or call functions within the placeholders:

let price = 1299.99
let taxRate = 0.2
let priceWithTax = "Ціна з ПДВ: \(price * (1 + taxRate))"
print(priceWithTax) // Виводить: Ціна з ПДВ: 1559.988

Deep Dive (Поглиблений Розбір):

Initially, programmers concatenated strings using +, but this got unwieldy. Swift’s string interpolation is more intuitive. Interpolation is more than just variables—it’s any valid expression, including function calls or calculations.

Alternatives like String(format:) exist, used mostly for formatting strings comprehensively (similar to printf in C).

How the interpolation works: Swift compiles your interpolated string into a series of appends to String. This is efficient, but there’s a performance consideration with very large strings or intense use.

See Also (Дивіться також):