Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I concatenate strings in Swift?

People also ask

Can you add strings in Swift?

In the apple documentation for swift it states that you concatenate 2 strings by using the additions operator e.g. : let string1 = "hello" let string2 = " there" var welcome = string1 + string2 4 // welcome now equals "hello there"

How do I append a character to a string in Swift?

for aCharacter: Character in aString { var str: String = "" var newStr: String = str. append(aCharacter) // ERROR ... }


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"

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


let the_string = "Swift"
let resultString = "\(the_string) is a new Programming Language"