Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

swift - What is type of 123_456_789?

I see in Swift examples values like 123_456_789, numbers with underscores. What type do these values have by default?

Does it depend on the type of the variable I assign them to? They look quite funny and new to me, so I wonder, how are they treated if they are thrown just like they are, without defining a type?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From the documentation (The Swift Programming Language -> Language Guide -> The Basics -> Numeric Literals):

Numeric literals can contain extra formatting to make them easier to read. Both integers and floats can be padded with extra zeros and can contain underscores to help with readability. Neither type of formatting affects the underlying value of the literal:

let paddedDouble = 000123.456
let oneMillion = 1_000_000
let justOverOneMillion = 1_000_000.000_000_1

So your 123_456_789 is a integer literal, and identical to 123456789. You can insert the underscores wherever you want, not only as a "thousands separator", such as 1_2_3_4_5_6_7_8_9 or 1_23_4567_89, if you like to write obfuscated code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...