DEV Community

Abd Sani
Abd Sani

Posted on

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.

Top comments (0)