Swift 5: Understanding of String Interpolation

Swift 5: Understanding of String Interpolation

Let’s deep dive into “StringInterpolation” which is a cool feature of Swift 5.

Let’s deep dive into “StringInterpolation” which is a cool feature of Swift 5.

With the help of “StringInterpolation”, we can define how the Objects appear in a string at the time of print the Object(while using print function and po while debugging).

While we print Struct, it prints the struct name followed by all its properties. Let’s see via code snippet.

struct AppUser{
    var firstName: String
    var lastName: String
}

let appUser = AppUser(firstName : "Payal",  lastName : "Maniyar")
print("User details: \(appUser)")


Output :

User details: AppUser(firstName: "Payal", lastName: "Maniyar")

But if we are working with classes and want to print the object, the behaviour is not the same as it is with Struct. Let’s see with the code snippet.

class Point {
    let x: Int, y: Int
    init( x: Int, y: Int){
        self.x = x
        self.y = y
    }
}

let p = Point(x: 21, y: 30)
print(p)

Output is :
__lldb_expr_11.Point

To print the objects of classes as well as the Struct, CustomStringConvertiblecomes into the picture. Let’s see its use with the code snippet.

class Point {
    let x: Int, y: Int
    init( x: Int, y: Int){
        self.x = x
        self.y = y
    }
}

let p = Point(x: 21, y: 30)
print(p)

extension Point: CustomStringConvertible {
    var description: String {
        return "Point : (\(x), \(y))"
    }
}

Output is :
Point : (21, 30)

If we use *CustomStringConvertible, *then we can print Object with implementing description property.

String Interpolation can also print the Object with various argument and various result. Let’s understand with code snippet:

class User {

    var firstName: String
    var lastName: String
    init (firstName: String,lastName: String){
        self.firstName = firstName
        self.lastName = lastName
    }
}
//StringInterpolation 1
extension String.StringInterpolation{
    mutating func appendInterpolation(_ user: User) {
        appendInterpolation("My name is : \(user.firstName) \(user.lastName)")
    }
}

//StringInterpolation 2
extension String.StringInterpolation{
    mutating func appendInterpolation(_ firstName: String,_ lastName: String) {
        appendInterpolation("First Name  : \(firstName) Last Name : \(lastName)")
    }
}

let user = User(firstName : "Payal ",  lastName : "Maniyar")
print("User details: \(user.firstName,user.lastName)")// This will use StringInterpolation 2
print("User details: \(user)")// This will use StringInterpolation 1

Output is :
User details: First Name  : Payal  Last Name : Maniyar
User details: My name is : Payal  Maniyar

In the above code snippet, the argument will decide which StringInterpolation extension to be used.

Let’s move on to more advanced usages… Your custom interpolation method can take as many parameters as you need, labelled or unlabeled. For example, we could add an interpolation to print numbers using various styles, like this:

import Foundation

extension String.StringInterpolation {
    mutating func appendInterpolation(_ number: Int, style: NumberFormatter.Style) {
        let formatter = NumberFormatter()
        formatter.numberStyle = style


        if let result = formatter.string(from: number as NSNumber) {
            appendLiteral(result)
        }
    }
}
 let number = Int.random(in: 0...100)
 let lucky1 = "The lucky number this week is \(number, style: .ordinal)."
 print(lucky1)

Output is : 

The lucky number this week is 100th.

You can call appendLiteral() as many times as you need, or even not at all if necessary. For example, we could add a string interpolation to repeat a string multiple times, like this:

 extension String.StringInterpolation {
    mutating func appendInterpolation(repeat str: String, _ count: Int) {
        for _ in 0 ..< count {
            appendLiteral(str)
        }
    }
}

print("\(repeat: "Do what you like\n ", 6)")

Do what you like
 Do what you like
 Do what you like
 Do what you like
 Do what you like
 Do what you like

And, as these are just regular methods, you can use Swift’s full range of functionality. For example, we might add an interpolation that joins an array of strings together, but if that array is empty execute a closure that returns a string instead:

extension String.StringInterpolation {
    mutating func appendInterpolation(_ values: [String], empty defaultValue: @autoclosure () -> String) {
        if values.count == 0 {
            appendLiteral(defaultValue())
        } else {
            appendLiteral(values.joined(separator: ", "))
        }
    }
}
func EmptyMsg () -> String {
        return "No one found"
}
var names = ["Harry", "Ron", "Hermione"]
print("List of students: \(names, empty: EmptyMsg()).")
names.removeAll()
print("List of students: \(names, empty: EmptyMsg() ).")

Output is :
List of students: Harry, Ron, Hermione.
List of students: No one found.

That’s it….

Hope now the use of StringInterpolation is clear now.

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Top iOS Mobile App Development Agency in New York

Are you looking for a [Top iOS Mobile App Development Agency in New York]**(https://www.appcluesinfotech.com/ios-app-develop**ment-company/ "Top iOS Mobile App Development Agency in New York") for your app projects? Then AppClues Infotech is the...

ECommerce Mobile App Development | Ecommerce Mobile App Development Services

We are leading ecommerce mobile application development company. Hire our ecommerce mobile app developer for your custom Ecommerce project at competitive rates. **Know about [Top ECommerce Mobile App Development...

Top iOS Mobile App Development Companies in the USA & India

Hire Top iOS app development companies in the USA and India. You can find the ultimate list of the best iOS app development companies in USA and India.