Search code examples
swiftconcatenation

Error concatenating characters in swift


I tried to concatenate two characters in Swift but it shows me the error

Binary operator can't be applied on two character operands.

let a: Character = "A"
let l: Character = "l"

let al = a + l 

Operator overloading is supported by Swift's Strings so why not Character?


Solution

  • If you really want/need to be able to "concatenate" 2 Character(s) using the + operator you can define this function.

    func + (left:Character, right:Character) -> String {
        return "\(left)\(right)"
    }
    

    As Skrundz said in its comment, an instance of Character can contain only 1 character so the output of the function is going to be a String.

    Now:

    let a : Character = "A"
    let b : Character = "B"
    let ab = a + b // -> the String "AB"