How does append function work in Swift?

匿名 (未验证) 提交于 2019-12-03 01:45:01

问题:

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 Strings: 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 !" 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!