为什么 String.append 不适用于像 "foo(bar)" 这样的格式化字符串?



在实现CustomStringConvertible时,我遇到了一个我不太理解的错误。

struct Name {
    let name: String?
}
extension Name: CustomStringConvertible {
    var description: String {
        var desc = ""
        if let name = name {
            desc.append("Page: (name)")
        }
        return desc
    }
}

这会导致以下错误:

error: cannot invoke 'append' with an argument list of type '(String)'
note: overloads for 'append' exist with these partially matching parameter lists: (UnicodeScalar), (Character)

看起来编译器不知道该使用哪个append函数的实现。

更改为

desc.append(name)

工作好。

一样
desc.appendContentsOf("Page: (name)")

这到底是为什么?

Swift 2中, String有两个append方法,它们取单个字符或Unicode标量作为参数:

public mutating func append(c: Character)
public mutating func append(x: UnicodeScalar)

这就是为什么desc.append("Page: (name)")不能编译(desc.append(name)也不能编译)。但

public mutating func appendContentsOf(other: String)

追加另一个字符串。或者使用

desc += "Page: (name)"

Swift 3中,这些方法被重命名为

public mutating func append(_ other: Character)
public mutating func append(_ other: UnicodeScalar)
public mutating func append(_ other: String)

然后是

desc.append("Page: (name)")

最新更新