Numeric Literals in Swift Programming Language

0

Numeric literals are values that represent numbers. They can be used in expressions to perform calculations or to initialize variables.

There are four types of numeric literals in Swift:

  • Integer literals
  • Floating-point literals
  • Complex literals
  • Boolean literals

Integer Literals

Integer literals represent whole numbers. They can be written in decimal, binary, octal, or hexadecimal format.

  • Decimal literals are the most common type of integer literal. They do not have any prefix.
  • Binary literals begin with a 0b prefix.
  • Octal literals begin with a 0o prefix.
  • Hexadecimal literals begin with a 0x prefix.

Here are some examples of integer literals:

123  // Decimal

0b101011  // Binary

0o77  // Octal

0x7b  // Hexadecimal

Floating-Point Literals

Floating-point literals represent numbers with decimal points. They can be written in decimal or hexadecimal format.

  • Decimal floating-point literals do not have any prefix.
  • Hexadecimal floating-point literals begin with a 0x prefix.

Here are some examples of floating-point literals:

123.45  // Decimal

0x1.23p2  // Hexadecimal

Complex Literals

Complex literals represent numbers with imaginary parts. They are written as a pair of floating-point literals separated by a + or - sign.

Here is an example of a complex literal:

1 + 2i

Boolean Literals

Boolean literals represent the values true and false. They are written as the keywords true and false.

Here are some examples of Boolean literals:

true

false

Numeric literals can be used in expressions to perform calculations. For example, the following expression adds two integer literals:

let x = 1 + 2

Numeric literals can also be used to initialize variables. For example, the following code initializes a variable named `x` to the value 10:

var x = 10

Numeric literals are a powerful tool that can be used to represent numbers in Swift code. They can be used in expressions to perform calculations and to initialize variables.

Post a Comment

0Comments
Post a Comment (0)