Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is type of 123_456_789?

Tags:

types

swift

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?

like image 886
Sergei Basharov Avatar asked Nov 23 '15 08:11

Sergei Basharov


1 Answers

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.

like image 54
Martin R Avatar answered Sep 20 '22 08:09

Martin R