Swift 中字符串插值和字符串初始化器的区别 [英] Difference between String interpolation and String initializer in Swift
问题描述
我可以使用字符串插值或字符串初始值设定项将 int、float、double 作为字符串读取.结果总是一样的.
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)
结果是一样的.d 的值为2e"
the result is same. d has value "2e"
我发现的唯一区别是字符串插值 () 可以在双引号内使用,而 String() 不能在双引号内使用.
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?
推荐答案
字符串插值 "\(item)"
为您提供对项目调用 description
的结果.String(item)
调用一个 String
初始值设定项并返回一个 String
值,该值经常与 String
相同你会从字符串插值中得到,但不能保证.
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"
这篇关于Swift 中字符串插值和字符串初始化器的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!