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)
提前致谢
推荐答案
在 Swift 中,没有字符字面量(例如 C 派生语言中的 'c'
),只有 String
文字.
In Swift, there is no character literal (such as 'c'
in C-derived languages), there are only String
literals.
然后,您在 String
s 上定义了两个函数:append
,用于附加单个字符,以及 extend
,用于附加整个细绳.所以这是有效的:
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("!")
如果你真的想使用append
,你可以通过调用强制将一个字符的String
文字转换为Character
Character
的构造函数:
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("!"))
或使用类型转换:
someString.append("!" as Character)
或者像使用额外变量一样使用类型注释:
or by using a type annotation as you did with an extra variable:
let exclamationMark: Character = "!"
someString.append(exclamationMark)
这篇关于Swift 中的 append 函数是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!