How do I concatenate strings in Swift?

How to concatenate string in Swift?

In Objective-C we do like

NSString *string = @"Swift";
NSString *resultStr = [string stringByAppendingString:@" is a new Programming Language"];

or

NSString *resultStr=[NSString stringWithFormat:@"%@ is a new Programming Language",string];

But I want to do this in Swift-language.


You can concatenate strings a number of ways:

let a = "Hello"
let b = "World"

let first = a + ", " + b
let second = "\(a), \(b)"

You could also do:

var c = "Hello"
c += ", World"

I'm sure there are more ways too.

Bit of description

let creates a constant. (sort of like an NSString). You can't change its value once you have set it. You can still add it to other things and create new variables though.

var creates a variable. (sort of like NSMutableString) so you can change the value of it. But this has been answered several times on Stack Overflow, (see difference between let and var).

Note

In reality let and var are very different from NSString and NSMutableString but it helps the analogy.


You can add a string in these ways:

  • str += ""
  • str = str + ""
  • str = str + str2
  • str = "" + ""
  • str = "\(variable)"
  • str = str + "\(variable)"

I think I named them all.


var language = "Swift" 
var resultStr = "\(language) is a new programming language"

This will work too:

var string = "swift"
var resultStr = string + " is a new Programming Language"