如何在Swift连接字符串?

在Objective-C中

NSString *string = @"Swift";
NSString *resultStr = [string stringByAppendingString:@" is a new Programming Language"];

or

NSString *resultStr=[NSString stringWithFormat:@"%@ is a new Programming Language",string];

但我想用swift语言来写。


当前回答

你也可以在Swift中使用stringByAppendingFormat。

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

其他回答

这也会起作用:

var string = "swift"
var resultStr = string + " is a new Programming Language"

非常简单:

let StringA = "Hello"
let StringB = "World"
let ResultString = "\(StringA)\(StringB)"
println("Concatenated result = \(ResultString)")

斯威夫特4.2

你也可以使用扩展:

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: " ")

结果:

"The Man"
"The"
"Man"

Xcode不接受与普通字符串一起添加的可选字符串。我写了这个扩展来解决这个问题:

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

然后你可以这样称呼它:

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

然而,你现在也可以这样做:

var str1: String?
var str1 = "hi"
var str2 = " my name is"
str1! += str2
var language = "Swift" 
var resultStr = "\(language) is a new programming language"