Combining Strings in Swift

sanijalal

Abd Sani

Posted on June 20, 2021

Combining Strings in Swift

More often than not in programming, you would need to manipulate Strings. In this post, I’m going to share the common techniques one can use to manipulate String in Swift.

Combining Strings

To combine or concatenate a string, one would only need to use the + operator.

Example:

let part1 = "Hello"
let part2 = "World"

let complete = part1 + " " + part2
print(complete) // This would print out "Hello World" 
Enter fullscreen mode Exit fullscreen mode

Alternatively, one could also use string interpolation for this.

let part1 = "Hello"
let part2 = "World"

let complete = "\(part1) \(part2)"
print(complete) // This would print out "Hello World"
Enter fullscreen mode Exit fullscreen mode

The outcome to these 2 approaches are the same. Is one method better than another? Not that I know of but it would make sense for you to discuss with your team members on which approach would be implemented in your codebase. As for my preference, I prefer to always use string interpolation as it is easier for me to visualise the final string in my head.

Reference:

Apple documentation on String.

💖 💪 🙅 🚩
sanijalal
Abd Sani

Posted on June 20, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related