C-formatting in Swift is similar to that in C: create a String type variable or constant with a c-formatting string,and display the variable or constant using the print() function.
let integerValue: Int = 1let doubleValue: Double = 2.33let characterValue: Character = "c"let stringValue: String = "str"let boolValue: Bool = truelet characterValueStr = String(characterValue) // (1) Character -> Stringlet stringtoprint = String(format: "%d %.2f %@ %@",integerValue,doubleValue,characterValueStr,stringValue)print(stringtoprint)
result:
1 2.33 c str
Something to notice:
A Bool type value cannot be printed with "%b".
A Character type value cannot be printed with "%c". To print a Character type value,convert it into a String type value using the String() initializer,see (1) above.
A String type value can be printed with "%@",not "%s".
Actually we can use the string interpolation in Swift together with the c-formatting,which also enables us to display the Character and Bool type value easily.
let doubleValueStr = String(format: "%.2f",doubleValue)print("\(integerValue) \(doubleValueStr) \(characterValue) \(stringValue) \(boolValue)")
result:
1 2.33 c str true
references:
(1) Swift:字符串格式化
(2) Swift - 数字格式化转成字符串(保留两位小数)
(3) 输出格式化
以上是内存溢出为你收集整理的C-formatting in Swift全部内容,希望文章能够帮你解决C-formatting in Swift所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)