9

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?

1 Answer 1

11

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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.