Swift-How to write a variable or a value that is changing between parenthesis

swift

53 观看

1回复

42 作者的声誉

(in swift language) For example " A + D " I want the string A to stay all the time but the value of D changes depending on let's say Hp, so when Hp is fd the string will be "A + fd" and etc

I mean like( "A + %s" % Hp ) for the string in python. Such as here: What does %s mean in Python?

作者: Mohan 的来源 发布者: 2017 年 12 月 27 日

回应 1


0

4287 作者的声誉

决定

If you are talking about %s, then it's a c-style formatting key, which awaits string variable or value in the list of arguments. In Swift, you compose strings using "\(variable)" syntax, which is called String interpolation, as explained in the documentation:

String Interpolation

String interpolation is a way to construct a new String value from a mix of constants, variables, literals, and expressions by including their values inside a string literal. You can use string interpolation in both single-line and multiline string literals. Each item that you insert into the string literal is wrapped in a pair of parentheses, prefixed by a backslash ():

Source: official documentation

Example:

var myVar = "World"
var string = "Hello \(myVar)"

With non-strings:

let multiplier = 3 
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)" 
// Output: message is "3 times 2.5 is 7.5"
作者: Hexfire 发布者: 2017 年 12 月 27 日
32x32