在实现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)")