211

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.

idmean
  • 14,540
  • 9
  • 54
  • 83
Rajneesh071
  • 30,846
  • 15
  • 61
  • 74
  • 2
    The Swift compiler cannot compile + very well. If you have a couple of + in a sentence then it may fail. Use \( ) – kelalaka May 31 '19 at 07:27

21 Answers21

366

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.

Community
  • 1
  • 1
Fogmeister
  • 76,236
  • 42
  • 207
  • 306
  • @Rajneesh071 Why would it give a compile time error? – Fogmeister Jun 04 '14 at 09:58
  • `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` create a variable. (sort of like NSMutableString) so you can change the value of it. But this has been answered several times on SO. Looks for `difference between let and var` – Fogmeister Jun 04 '14 at 10:06
  • let a = "Hello" let b = "World" let first = a + ", " + b Does not work, this is what works, let first = "\(a), \(b)" . You will get a runtime error with the first method – Joseph Oct 01 '14 at 21:15
  • 1
    @Joseph works fine for me. http://i.imgur.com/T15s4Sp.png Thanks for the down vote though. – Fogmeister Oct 02 '14 at 07:19
  • @Fogmeister what version of xCode are you using? Doesnt work on xCode 6.3 Beta, maybe its working on the latest version – Joseph Oct 02 '14 at 10:32
  • @Joseph why would you down vote my correct answer based on testing from an old beta? The latest beta was something like beta 7 (6.0 not 6.3, there is no such thing). The latest version of Xcode is the actual release version. It was released about 3 weeks ago. Why are you still using a beta? – Fogmeister Oct 02 '14 at 10:35
  • this kind of concating `let c = a + "," + b` is giving me error: Expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions – Matt Oct 18 '14 at 04:14
  • Does anybody have an opinion which of both is preferable: "first" or "second" ? – alex da franca Dec 03 '15 at 14:09
  • for me its says Binary operator '+' cannot be applied to operands of type 'Any?' and 'String' – KkMIW Jul 17 '19 at 20:42
  • @KkMIW that’s because you can’t add `Any?` and `String`. You need to have two Strings. – Fogmeister Jul 17 '19 at 21:06
67

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.

Arbitur
  • 38,684
  • 22
  • 91
  • 128
38
var language = "Swift" 
var resultStr = "\(language) is a new programming language"
idmean
  • 14,540
  • 9
  • 54
  • 83
yoeriboven
  • 3,541
  • 3
  • 25
  • 40
13

This will work too:

var string = "swift"
var resultStr = string + " is a new Programming Language"
CW0007007
  • 5,681
  • 4
  • 26
  • 31
11

\ this is being used to append one string to another string.

var first = "Hi" 
var combineStr = "\(first) Start develop app for swift"

You can try this also:- + keyword.

 var first = "Hi" 
 var combineStr = "+(first) Start develop app for swift"

Try this code.

Jitendra
  • 5,055
  • 2
  • 22
  • 42
10
let the_string = "Swift"
let resultString = "\(the_string) is a new Programming Language"
Bagvendt
  • 123
  • 1
  • 8
9

Very Simple:

let StringA = "Hello"
let StringB = "World"
let ResultString = "\(StringA)\(StringB)"
println("Concatenated result = \(ResultString)")
Rajesh Loganathan
  • 11,129
  • 4
  • 78
  • 90
9

You can now use stringByAppendingString in Swift.

var string = "Swift"
var resultString = string.stringByAppendingString(" is new Programming Language")
Mark Moeykens
  • 15,915
  • 6
  • 63
  • 62
5

Xcode didn't accept optional strings added with a normal string. I wrote this extensions to solve that problem:

extension String {
    mutating func addString(str: String) {
        self = self + str
    }
}

Then you can call it like:

var str1: String?
var str1 = "hi"
var str2 = " my name is"
str1.addString(str2)
println(str1) //hi my name is

However you could now also do something like this:

var str1: String?
var str1 = "hi"
var str2 = " my name is"
str1! += str2
idmean
  • 14,540
  • 9
  • 54
  • 83
Esqarrouth
  • 38,543
  • 21
  • 161
  • 168
  • Which part? Are you familiar with extentions? – Esqarrouth Sep 02 '15 at 13:16
  • Yes, I was wondering what is gained by converting '+' in 'addString()'. If I remember correctly this way would also give you a warning instead of a compiler error if used on non mutable variable. Otherwise it's obfuscating what is going on and, IMO, nothing is easier/faster to read than '+'. Truth is there might be a reason I am blind to and that is why I was asking why this way is 'recommended' – user3802077 Sep 08 '15 at 00:01
  • I used this when xcode didn't accept adding an optional string with a normal string. it still doesn't do that directly but now it works when you force unwrap the string, so this extension is useless atm. i'll delete it after you read this left me a comment – Esqarrouth Sep 08 '15 at 10:53
  • Thanks for the explantion :). Not sure what is considered better but by adding the context to your answer it would have value even tough currently it may not be as useful as before. – user3802077 Sep 08 '15 at 16:00
5

Swift 5

You can achieve it using appending API. This returns a new string made by appending a given string to the receiver.

API Details : here

Use:

var text = "Hello"
text = text.appending(" Namaste")

Result:

Hello
Hello Namaste
Vittal Pai
  • 3,317
  • 25
  • 36
4

It is called as String Interpolation. It is way of creating NEW string with CONSTANTS, VARIABLE, LITERALS and EXPRESSIONS. for examples:

      let price = 3
      let staringValue = "The price of \(price) mangoes is equal to \(price*price) "

also

let string1 = "anil"
let string2 = "gupta"
let fullName = string1 + string2  // fullName is equal to "anilgupta"
or 
let fullName = "\(string1)\(string2)" // fullName is equal to "anilgupta"

it also mean as concatenating string values.

Hope this helps you.

Anil Gupta
  • 1,155
  • 1
  • 19
  • 26
4

I just switched from Objective-C to Swift (4), and I find that I often use:

let allWords = String(format:"%@ %@ %@",message.body!, message.subject!, message.senderName!)
Sjakelien
  • 2,255
  • 3
  • 25
  • 43
3

To print the combined string using

Println("\(string1)\(string2)")

or String3 stores the output of combination of 2 strings

let strin3 = "\(string1)\(string2)"
Luís Cruz
  • 14,780
  • 16
  • 68
  • 100
Pvni
  • 65
  • 7
3

One can also use stringByAppendingFormat in Swift.

var finalString : NSString = NSString(string: "Hello")
finalString = finalString.stringByAppendingFormat("%@", " World")
print(finalString) //Output:- Hello World
finalString = finalString.stringByAppendingFormat("%@", " Of People")
print(finalString) //Output:- Hello World Of People
Pushpa Y
  • 1,010
  • 1
  • 12
  • 20
3

Swift 4.2

You can also use an extension:

extension Array where Element == String? {
    func compactConcate(separator: String) -> String {
        return self.compactMap {
            if let unwrappedString = $0,
               unwrappedString.isEmpty {
                return nil
            } else {
                return $0
            }
        }
        .joined(separator: separator)
    }
}

Use:

label.text = [m.firstName, m.lastName].compactConcate(separator: " ")

Result:

"The Man"
"The"
"Man"
Nike Kov
  • 12,630
  • 8
  • 75
  • 122
3

Concatenation refers to the combining of Strings in Swift. Strings may contain texts, integers, or even emojis! There are many ways to String Concatenation. Let me enumerate some:

Same String

Using +=

This is useful if we want to add to an already existing String. For this to work, our String should be mutable or can be modified, thus declaring it as a Variable. For instance:

var myClassmates = "John, Jane"
myClassmates += ", Mark" // add a new Classmate
// Result: "John, Jane, Mark"

Different Strings

If we want to combine different Strings together, for instance:

let oldClassmates = "John, Jane" 
let newClassmate = "Mark"

We can use any of the following:

1) Using +

let myClassmates = oldClassmates + ", " + newClassmate
// Result: "John, Jane, Mark"

Notice that the each String may be a Variable or a Constant. Declare it as a Constant if you're only gonna change the value once.

2) String Interpolation

let myClassmates = "\(oldClassmates), \(newClassmate)"
// Result: "John, Jane, Mark"

3) Appending

let myClassmates = oldClassmates.appending(newClassmate)
// Result: "John, Jane, Mark"

Refer to Strings & Characters from the Swift Book for more.

Update: Tested on Swift 5.1

mjoe7
  • 134
  • 6
2

From: Matt Neuburg Book “iOS 13 Programming Fundamentals with Swift.” :

To combine (concatenate) two strings, the simplest approach is to use the + operator:

let s = "hello"
let s2 = " world"
let greeting = s + s2

This convenient notation is possible because the + operator is overloaded: it does one thing when the operands are numbers (numeric addition) and another when the operands are strings (concatenation). The + operator comes with a += assignment shortcut; naturally, the variable on the left side must have been declared with var:

var s = "hello"
let s2 = " world"
s += s2

As an alternative to +=, you can call the append(_:) instance method:

var s = "hello"
let s2 = " world"
s.append(s2)

Another way of concatenating strings is with the joined(separator:) method. You start with an array of strings to be concatenated, and hand it the string that is to be inserted between all of them:

let s = "hello"
let s2 = "world"
let space = " "
let greeting = [s,s2].joined(separator:space)
H S W
  • 6,310
  • 4
  • 25
  • 36
2

Swift concatenate strings

Several words about performance

UI Testing Bundle on iPhone 7(real device), iOS 14, -Onone(debug, without optimizations)[About]

var result = ""
for i in 0...count {
    <concat_operation>
}

Count = 5_000

//Append
result.append(String(i))                         //0.007s 39.322kB

//Plus Equal
result += String(i)                              //0.006s 19.661kB

//Plus
result = result + String(i)                      //0.130s 36.045kB

//Interpolation
result = "\(result)\(i)"                         //0.164s 16.384kB

//NSString
result = NSString(format: "%@%i", result, i)     //0.354s 108.142kB

//NSMutableString
result.append(String(i))                         //0.008s 19.661kB

Disable next tests:

  • Plus up to 100_000 ~10s
  • interpolation up to 100_000 ~10s
  • NSString up to 10_000 -> memory issues

Count = 1_000_000

//Append
result.append(String(i))                         //0.566s 5894.979kB

//Plus Equal
result += String(i)                              //0.570s 5894.979kB

//NSMutableString
result.append(String(i))                         //0.751s 5891.694kB

*Note about Convert Int to String

Source code

import XCTest

class StringTests: XCTestCase {
    let count = 1_000_000
    
    let metrics: [XCTMetric] = [
        XCTClockMetric(),
        XCTMemoryMetric()
    ]
    
    let measureOptions = XCTMeasureOptions.default
    
    override func setUp() {
        measureOptions.iterationCount = 5
    }
    
    func testAppend() {
        var result = ""
        measure(metrics: metrics, options: measureOptions) {
            for i in 0...count {
                result.append(String(i))
            }
        }
    }
    
    func testPlusEqual() {
        var result = ""
        measure(metrics: metrics, options: measureOptions) {
            for i in 0...count {
                result += String(i)
            }
        }
    }
    
    func testPlus() {
        var result = ""
        measure(metrics: metrics, options: measureOptions) {
            for i in 0...count {
                result = result + String(i)
            }
        }
    }
    
    func testInterpolation() {
        var result = ""
        measure(metrics: metrics, options: measureOptions) {
            for i in 0...count {
                result = "\(result)\(i)"
            }
        }
    }
    
    //Up to 10_000
    func testNSString() {
        var result: NSString =  ""
        measure(metrics: metrics, options: measureOptions) {
            for i in 0...count {
                result = NSString(format: "%@%i", result, i)
            }
        }
    }
    
    func testNSMutableString() {
        let result = NSMutableString()
        measure(metrics: metrics, options: measureOptions) {
            for i in 0...count {
                result.append(String(i))
            }
        }
    }
}

yoAlex5
  • 29,217
  • 8
  • 193
  • 205
2

Swift 5:

Array of strings into a Single string

let array = ["Ramana","Meharshi","Awareness","Oneness","Enlightnment","Nothing"]
let joined = array.joined(separator: ",")
Sourabh Sharma
  • 8,222
  • 5
  • 68
  • 78
1

You could use SwiftString (https://github.com/amayne/SwiftString) to do this.

"".join(["string1", "string2", "string3"]) // "string1string2string"
" ".join(["hello", "world"]) // "hello world"

DISCLAIMER: I wrote this extension

eurobrew
  • 77
  • 4
0

In Swift 5 apple has introduces Raw Strings using # symbols.

Example:

print(#"My name is "XXX" and I'm "28"."#)
let name = "XXX"
print(#"My name is \#(name)."#)

symbol # is necessary after \. A regular \(name) will be interpreted as characters in the string.

Yogendra Singh
  • 2,063
  • 25
  • 20