Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between String interpolation and String initializer in Swift

Tags:

string

swift

I can read an int, float, double as a string using string interpolation or String initializer. result is always the same.

var a: Int = 2

var c: Character = "e"

var d: String = "\(a)\(c)"

OR

var d: String = String(a) + String(c)

the result is same. d has value "2e"

The only difference that I found is that string interpolation () can be used inside double quotes, whereas String() cannot be used inside double quotes.

Is that all? Am I missing something here?

like image 760
KawaiKx Avatar asked Jul 30 '16 16:07

KawaiKx


People also ask

What is the difference between string interpolation and string concatenation?

You can think of string concatenation as gluing strings together. And, you can think of string interpolation without strings as injecting strings inside of other strings.

What is string interpolation in Swift?

String interpolation is a way to construct a new String value from a mix of constants, variables, literals, and expressions by including their values inside a string literal. You can use string interpolation in both single-line and multiline string literals.

What is string describing in Swift?

The String(describing:) initializer is the preferred way to convert an instance of any type to a string. If the passed instance conforms to CustomStringConvertible , the String(describing:) initializer and the print(_:) function use the instance's custom description property.


1 Answers

String interpolation "\(item)" gives you the result of calling description on the item. String(item) calls a String initializer and returns a String value, which frequently is the same as the String you would get from string interpolation, but it is not guaranteed.

Consider the following contrived example:

class MyClass: CustomStringConvertible {
    var str: String

    var description: String { return "MyClass - \(str)" }

    init(str: String) {
        self.str = str
    }
}

extension String {
    init(_ myclass: MyClass) {
        self = myclass.str
    }
}

let mc = MyClass(str: "Hello")
String(mc)  // "Hello"
"\(mc)"     // "MyClass - Hello"
like image 92
vacawama Avatar answered Oct 14 '22 12:10

vacawama