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.

Top iOS Mobile App Development Agency in New York

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

Are you looking for a Top iOS Mobile App Development Agency in New York for your app projects? Then AppClues Infotech is the reliable & trustworthy iOS mobile app development company in New York offering excellent iOS, iPhone, iPad and wearable app development, etc. technology solutions to their clients at an affordable price.

We believed to be one of the successful providers of iOS app development services. We have a dedicated team of developers and designers who have high knowledge and the best strength of developing any type of iOS apps.

Our iOS App Development Service:
• iOS App UX / UI Design
• Native & Hybrid iOS App Development
• App Redesigning
• iOS App Programming
• App Testing for flawless Performance
• App Support & Maintenance

For more info:
Visit: https://www.appcluesinfotech.com/
Email: [email protected]
Call: +1-978-309-9910

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

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 Company

Top Mobile App Development Agency in Massachusetts

Top Mobile App Development Agency in Massachusetts

**Looking for Top Mobile App Development Agency at reasonable rates?** AppClues Studio is one of the top Mobile App Development Agencies in Massachusetts. We offer user-oriented mobile solutions to our clients globally. We offer Mobile app...

Looking for Top Mobile App Development Agency at reasonable rates?

AppClues Studio is one of the top Mobile App Development Agencies in Massachusetts. We offer user-oriented mobile solutions to our clients globally.

We offer Mobile app development services like iOS app development, Android app development, M-commerce development, Cross-Platform mobile app development, AR & VR app development, IoT app development, Wallet app development, Hybrid app development etc.

Why Choose AppClues Studio?
• Domain Expertise
• On-time Delivery
• 24/7 Support
• Aesthetic Designs
• Agile Development
• Smooth Handover

If you looking for your mobile application development, then get in touch with us!
Visit: https://appcluesstudio.com/mobile-applications-development-company-massachusetts
Email: [email protected]
Contact No.: +1-978-309-9910