ielyamani
ielyamani

Reputation: 18591

String interpolation in Swift

A function in swift takes any numeric type in Swift (Int, Double, Float, UInt, etc). the function converts the number to a string

the function signature is as follows :

func swiftNumbers <T : NumericType> (number : T) -> String {
    //body
}

NumericType is a custom protocol that has been added to numeric types in Swift.

inside the body of the function, the number should be converted to a string:

I use the following

var stringFromNumber = "\(number)"

which is not so elegant, PLUS : if the absolute value of the number is strictly inferior to 0.0001 it gives this:

"\(0.000099)" //"9.9e-05"

or if the number is a big number :

"\(999999999999999999.9999)" //"1e+18"

is there a way to work around this string interpolation limitation? (without using Objective-C)

P.S :

NumberFormater doesn't work either

import Foundation

let number : NSNumber = 9_999_999_999_999_997

let formatter = NumberFormatter()
formatter.minimumFractionDigits = 20
formatter.minimumIntegerDigits = 20
formatter.minimumSignificantDigits = 40

formatter.string(from: number) // "9999999999999996.000000000000000000000000"

let stringFromNumber = String(format: "%20.20f", number) // "0.00000000000000000000"

Upvotes: 9

Views: 18550

Answers (3)

AshWinee Dhakad
AshWinee Dhakad

Reputation: 681

String and Characters conforms to StringInterpolationProtocol protocol which provide more power to the strings.

StringInterpolationProtocol - "Represents the contents of a string literal with interpolations while it’s being built up."

String interpolation has been around since the earliest days of Swift, but in Swift 5.0 it’s getting a massive overhaul to make it faster and more powerful.

let name = "Ashwinee Dhakde"
print("Hello, I'm \(name)")

Using the new string interpolation system in Swift 5.0 we can extend String.StringInterpolation to add our own custom interpolations, like this:

extension String.StringInterpolation {
    mutating func appendInterpolation(_ value: Date) {
       let formatter = DateFormatter()
       formatter.dateStyle = .full

       let dateString = formatter.string(from: value)
       appendLiteral(dateString)
    }
}

Usage: print("Today's date is \(Date()).")

We can even provide user-defined names to use String-Interpolation, let's understand with an example.

extension String.StringInterpolation {
    mutating func appendInterpolation(JSON JSONData: Data) {
        guard
            let JSONObject = try? JSONSerialization.jsonObject(with: JSONData, options: []),
            let jsonData = try? JSONSerialization.data(withJSONObject: JSONObject, options: .prettyPrinted) else {
            appendInterpolation("Invalid JSON data")
            return
        }
        appendInterpolation("\n\(String(decoding: jsonData, as: UTF8.self))")
    }
}


print("The JSON is \(JSON: jsonData)")

Whenever we want to provide "JSON" in the string interpolation statement, it will print the .prettyPrinted

Isn't it cool!!

Upvotes: 2

Anitha
Anitha

Reputation: 149

Swift String Interpolation

1) Adding different types to a string

2) Means the string is created from a mix of constants, variables, literals or expressions.

Example:

let length:Float = 3.14
var breadth = 10
var myString = "Area of a rectangle is length*breadth"
myString = "\(myString) i.e. = \(length)*\(breadth)"    

Output:

3.14
10
Area of a rectangle is length*breadth
Area of a rectangle is length*breadth i.e. = 3.14*10

Upvotes: 9

chrisinsfo
chrisinsfo

Reputation: 402

Use the Swift String initializer: String(format: <#String#>, arguments: <#[CVarArgType]#>) For example: let stringFromNumber = String(format: "%.2f", number)

Upvotes: 5

Related Questions