加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C-formatting in Swift

发布时间:2020-12-16 09:12:39 所属栏目:百科 来源:网络整理
导读: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

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 = 1
let doubleValue: Double = 2.33
let characterValue: Character = "c"
let stringValue: String = "str"
let boolValue: Bool = true

let characterValueStr = String(characterValue) // (1) Character -> String

let 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) 输出格式化

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读