3.2. Operator overloading

Operator overloading is a way of saying that an arithmetic operator like + has another meaning depending on different data types. For example, we can concatenate two strings, or join two arrays with + operator. For example,

let firstName = "Sakib"
let lastName = "Miazi"
let fullName = firstName + " " + lastName
print(fullName)

let listNumOne = [1,2,3]
let listNumTwo = [4,5,6]
let listNum = listNumOne + listNumTwo
print(listNum)

It prints:

Sakib Miazi
[1, 2, 3, 4, 5, 6]

Now a question: what if you write the following code:

let listOne = [1,2,3]
let listTwo = ["four", "five"]
let listOneTwo = listOne + listTwo

would it work? 😉

Last updated

Was this helpful?