简体   繁体   English

Swift中的append函数如何工作?

[英]How does append function work in Swift?

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 提前致谢

In Swift, there is no character literal (such as 'c' in C-derived languages), there are only String literals. 在Swift中,没有字符文字(例如,C语言中的'c' ),只有String文字。

Then, you have two functions defined on String s: append , to append a single character, and extend , to append a whole String. 然后,您在String定义了两个函数: append ,以附加单个字符, extend ,以附加整个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: 如果您确实想使用append ,则可以通过调用Character的构造函数来强制将一个字符的String文字转换为Character

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)

String has 2 overloaded append(_:) String有2个重载的append(_:)

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

and both Character and UnicodeScalar conforms UnicodeScalarLiteralConvertible 而且CharacterUnicodeScalar符合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 . 在这种情况下是UnicodeScalarLiteral So, the compiler can not determine "!" 因此,编译器无法确定"!" is Character or UnicodeScalar , and which append(_:) method should be invoked. CharacterUnicodeScalar ,应调用哪个append(_:)方法。 That's why you must specify it explicitly. 因此,您必须明确指定它。


You can see: "!" 您会看到: "!" can be a UnicodeScalar literal by this code: 通过以下代码可以是UnicodeScalar文字:

struct MyScalar: UnicodeScalarLiteralConvertible {
    init(unicodeScalarLiteral value: UnicodeScalar) {
        println("unicode \(value)")
    }
}

"!" as MyScalar // -> prints "unicode !"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM