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.

swift mobile-apps ios

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How To Succeed In Mobile App Wireframe Design?

This article covers everything about mobile app wireframe design: what to do and what not, tools used in designing a mobile or web app wireframe, and more.

How long does it take to develop/build an app?

This article covers A-Z about the mobile and web app development process and answers your question on how long does it take to develop/build an app.

Best Mobile App Development Company | Android and iOS Apps

iPrism Tech is a one of the best and offshore mobile app development company in India, Saudi Arabia and USA. We are a major providers of android, iphone and ipad mobile app development services at economical prices.

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...

Hire iOS App Developer

Are you looking to transform your idea into an iPhone application? Hire iPhone programmer team from **[HourlyDeveloper.io](https://hourlydeveloper.io/ "HourlyDeveloper.io")** to ensure the best results, utilizing all the latest trends in iOS app...