Search code examples
swiftstringconcatenationstring-concatenation

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.


Solution

  • 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.