join two strings in swift

To join two strings in Swift, you can use the + operator or the compound assignment operator +=. Here's an example:

main.swift
let firstName = "John"
let lastName = "Doe"

let fullName = firstName + " " + lastName
print(fullName) // Output: "John Doe"

// Alternatively, you can use the += operator
var greeting = "Hello, "
greeting += fullName
print(greeting) // Output: "Hello, John Doe"
263 chars
11 lines

In the example above, we first declare two string variables firstName and lastName. Then, we use the + operator to concat the two strings and assign the result to a new variable fullName. We print the result to the console to verify the output.

Alternatively, we can use the += operator to concat a string to an existing variable. We first declare a variable greeting and assign it the value "Hello, ". Then, we use the compound assignment operator += to append the fullName variable to greeting. Finally, we print the result to the console.

related categories

gistlibby LogSnag