How to concatenate string in Swift?
In Objective-C
we do like
NSString *string = @\"Swift\";
NSString *resultStr = [string stringByAppen
You can now use stringByAppendingString in Swift.
var string = "Swift"
var resultString = string.stringByAppendingString(" is new Programming Language")
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
You can also use an extension:
extension Array where Element == String? {
func compactConcate(separator: String) -> String {
return self.compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: separator)
}
}
Use:
label.text = [m.firstName, m.lastName].compactConcate(separator: " ")
Result:
"The Man"
"The"
"Man"
This will work too:
var string = "swift"
var resultStr = string + " is a new Programming Language"
Very Simple:
let StringA = "Hello"
let StringB = "World"
let ResultString = "\(StringA)\(StringB)"
println("Concatenated result = \(ResultString)")
let the_string = "Swift"
let resultString = "\(the_string) is a new Programming Language"