我试图在Swift中连接两个字符,但它显示错误
二进制运算符不能应用于两个字符操作数。
let a: Character = "A"
let l: Character = "l"
let al = a + l
Swift的字符串支持运算符重载,为什么不使用Character?
答案 0 :(得分:4)
如果你真的想要/需要能够'#34;连接" 2 Character(s)
使用+
运算符,您可以定义此函数。
func + (left:Character, right:Character) -> String {
return "\(left)\(right)"
}
正如Skrundz在评论中所说,Character
的实例只能包含1个字符,因此函数的输出将是String
。
现在:
let a : Character = "A"
let b : Character = "B"
let ab = a + b // -> the String "AB"
答案 1 :(得分:0)
列出连接两个字符的大多数可能性
let character1: Character = "a"
let character2: Character = "b"
let result = String(character1) + String(character2)
let result = "\(character1)" + "\(character2)"
let result = "\(character1)\(character2)"
let result = "" + [character1, character2]
var result = ""; result += [character1, character2]
var result = ""; result.append(character1); result.append(character2)
var result = [String(character1), String(character2)].joined()