Difference between String interpolation and String initializer in Swift

后端 未结 1 1223
广开言路
广开言路 2020-12-09 20:44

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 =          


        
相关标签:
1条回答
  • 2020-12-09 21: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"
    
    0 讨论(0)
提交回复
热议问题