The Basics
- let age = 25
- print("You are \(age)")
We take it for granted these days but it was a huge quality of life improvement over the syntax we previously had.
- [NSString stringWithFormat:@"%ld", (long)unreadCount];
But it’s also an important performance improvement because the alternative was to write string joining code like this.
- let all = s1 + s2 + s3 + s4
String interpolation hasn’t changed much since Swift 1.0, with the only real change coming in Swift 2.1 where we gained the ability to use string literals in interpolations, like this.
- print("Hi, \(user ?? "Anonymous")")
- let age = 25
- let age = 25
- print("HI, I'm \(age).")
- OUTPUT : HI, I'm 25.
- extension String.StringInterpolation {
- mutating func appendInterpolation(_ value: Int) {
- let formatter = NumberFormatter()
- formatter.numberStyle = .spellOut
- if let result = formatter.string(from: value as NSNumber) {
- appendLiteral(result)
- }
- }
- }
- print("HI, I'am \(age).")
- OUTPUT : HI, I'am twenty-five.
- print("Today's date is \(Date()).")
- OUTPUT : Today's date is 2019-05-28 11:26:18 +0000.
- extension String.StringInterpolation {
- mutating func appendInterpolation(_ value: Date) {
- let formatter = DateFormatter()
- formatter.dateStyle = .full
- let dateString = formatter.string(from: value)
- appendLiteral(dateString)
- }
- }
- print("Today's date is \(Date()).")
- OUTPUT : Today's date is Tuesday, May 28, 2019.
Interpolation with parameters
- extension String.StringInterpolation {
- mutating func appendInterpolation(twitter: String) {
- appendLiteral("<a href=\"https://twitter.com/\(twitter)\">@\(twitter)</a>")
- }
- }
- print("You should follow me on Twitter: \(twitter: "praveshdubey99").")
- OUTPUT : You should follow me on Twitter: <a href="https://twitter.com/praveshdubey99">@praveshdubey99</a>.
- extension String.StringInterpolation {
- mutating func appendInterpolation(format value: Int, using style: NumberFormatter.Style) {
- let formatter = NumberFormatter()
- formatter.numberStyle = style
- if let result = formatter.string(from: value as NSNumber) {
- appendLiteral(result)
- }
- }
- }
- print("Hi, I'm \(format: age, using: .spellOut).")
- OUTPUT : Hi, I'm twenty-five.

Join the conversation! Your thoughts help the community grow.