如何在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语言来写。


当前回答

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

其他回答

这也会起作用:

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

我刚从Objective-C切换到Swift(4),我发现我经常使用:

let allWords = String(format:"%@ %@ %@",message.body!, message.subject!, message.senderName!)

它被称为字符串插值。 它是用常量,变量,字面量和表达式创建新字符串的方法。 例子:

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

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"

它也意味着串联字符串值。

希望这对你有所帮助。

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

你也可以在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