Append String in Swift
Solution 1:
Its very simple:
For ObjC:
NSString *string1 = @"This is";
NSString *string2 = @"Swift Language";
ForSwift:
let string1 = "This is"
let string2 = "Swift Language"
For ObjC AppendString:
NSString *appendString=[NSString stringWithFormat:@"%@ %@",string1,string2];
For Swift AppendString:
var appendString1 = "\(string1) \(string2)"
var appendString2 = string1+string2
Result:
print("APPEND STRING 1:\(appendString1)")
print("APPEND STRING 2:\(appendString2)")
Complete Code In Swift:
let string1 = "This is"
let string2 = "Swift Language"
var appendString = "\(string1) \(string2)"
var appendString1 = string1+string2
print("APPEND STRING1:\(appendString1)")
print("APPEND STRING2:\(appendString2)")
Solution 2:
In Swift, appending strings is as easy as:
let stringA = "this is a string"
let stringB = "this is also a string"
let stringC = stringA + stringB
Or you can use string interpolation.
let stringC = "\(stringA) \(stringB)"
Notice there will now be whitespace between them.
Note: I see the other answers are using var
a lot. The strings aren't changing and therefore should be declared using let
. I know this is a small exercise, but it's good to get into the habit of best practices. Especially because that's a big feature of Swift.
Solution 3:
let string2 = " there"
var instruction = "look over"
choice 1 :
instruction += string2;
println(instruction)
choice 2:
var Str = instruction + string2;
println(Str)
ref this