问题
Can someone explain me what is wrong with this statement.
var someString = "Welcome"
someString.append("!")
However this works when I replace the code with,
var someString = "Welcome"
let exclamationMark : Character = "!"
someString.append(exclamationMark)
Thanks in advance
回答1:
In Swift, there is no character literal (such as 'c'
in C-derived languages), there are only String
literals.
Then, you have two functions defined on String
s: append
, to append a single character, and extend
, to append a whole String. So this works:
var someString = "Welcome"
someString.extend("!")
If you really want to use append
, you can force a one-char String
literal to be turned into a Character
either by calling Character
's constructor:
someString.append(Character("!"))
or by using a type conversion:
someString.append("!" as Character)
or by using a type annotation as you did with an extra variable:
let exclamationMark: Character = "!"
someString.append(exclamationMark)
回答2:
String
has 2 overloaded append(_:)
mutating func append(x: UnicodeScalar)
mutating func append(c: Character)
and both Character
and UnicodeScalar
conforms UnicodeScalarLiteralConvertible
enum Character : ExtendedGraphemeClusterLiteralConvertible, Equatable, Hashable, Comparable {
/// Create an instance initialized to `value`.
init(unicodeScalarLiteral value: Character)
}
struct UnicodeScalar : UnicodeScalarLiteralConvertible {
/// Create an instance initialized to `value`.
init(unicodeScalarLiteral value: UnicodeScalar)
}
"!"
in this case is a UnicodeScalarLiteral
. So, the compiler can not determine "!"
is Character
or UnicodeScalar
, and which append(_:)
method should be invoked. That's why you must specify it explicitly.
You can see: "!"
can be a UnicodeScalar literal by this code:
struct MyScalar: UnicodeScalarLiteralConvertible {
init(unicodeScalarLiteral value: UnicodeScalar) {
println("unicode \(value)")
}
}
"!" as MyScalar // -> prints "unicode !"
来源:https://stackoverflow.com/questions/28495802/how-does-append-function-work-in-swift