In this tutorial you will learn about the Swift Literals and its application with practical example.
Swift Literals
Literals are used to express certain values within the source code of the program. In Swift, literals can be used to represent value of an integer, floating-point number, or string type. Here are some of valid literals examples –
1 2 3 |
15 // Integer literal 10.3959 // Floating-point literal "Hello, world!" // String literal |
In Swift, literals can be of following types –
Integer Literals
Integer literal are used to represent a decimal, binary, octal, or hexadecimal constant value. In Swift, a binary literals starts with 0b, octal literals starts with 0o, and hexadecimal literals starts with 0x and rest every integer literal is a decimal literals.
Example:-
1 2 3 4 |
let decInt = 18 // 18 in decimal notation let binInt = 0b10010 // 18 in binary notation let octInt = 0o22 // 18 in octal notation let hexInt = 0x12 // 18 in hexadecimal notation |
Floating-point Literals
A floating-point literal is used to represent value for a float and double variable or constants. A floating-point literals can be represented either in decimal form or hexadecimal form.
A decimal floating-point literals is composed of a sequence of decimal digits followed by either a decimal fraction, a decimal exponent, or both.While, a hexadecimal floating-point literals composed of a 0x prefix, followed by an optional hexadecimal fraction, followed by a hexadecimal exponent.
Example1:-
1 2 3 4 |
let varFloat1 = 15.51 let varFloat2 = 5.15e2 print(varFloat1) print(varFloat2) |
Output:-
1 2 |
15.51 515.0 |
Example2:-
1 2 3 4 |
let varFloat1 = 0xFp11 let varFloat2 = 0xFp-13 print(varFloat1) print(varFloat2) |
Output:-
1 2 |
30720.0 0.0018310546875 |
String & Character literals
String literals are represented as a sequence of characters surrounded by double quotes and a character literal is represented as a single character surrounded by double quotes.
Example:-
1 2 |
let chr:Character = "S" let str:String = "W3Adda Swift" |
Here, “S” is a character literal and “W3Adda Swift” is a string literal.
Boolean Literals
Boolean literals are used to represent true and false value.
Example:-
1 |
let flg:Bool = true |
Here, true is a boolean literal which is assigned to the constant flg.