Wednesday, June 8, 2016

Swift Programming - Literals

A literal is the representation of a value of an integer, floating-point number, or string type.

The below are examples of literals.

Integer Literal
42

Floating-point literal
2.34354646

String Literal
"Hello world"

Integer Literals


An integer literal can be a decimal, binary, octal, or hexadecimal constant. Binary literals begin with 0b, octal literals begin with 0o, and hexadecimal literals begin with 0x and nothing for decimal.

Examples:

let decimalInteger = 18            
let binaryInteger = 0b10001        
let octalInteger = 0o21          
let hexadecimalInteger = 0x11    

Floating-point Literals


A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or hexadecimal form.

Decimal floating-point literals consist of a sequence of decimal digits followed by either a decimal fraction, a decimal exponent, or both.

Hexadecimal floating-point literals consist of a 0x prefix, followed by an optional hexadecimal fraction, followed by a hexadecimal exponent.

Example:

let decimalDouble = 15.1457
let exponentDouble = 1.21875e1
let hexadecimalDouble = 0xC.3p0

String Literals


A string literal is a sequence of characters surrounded by double quotes, with the following form

"characters"

String literals cannot contain an unescaped double quote ("), an unescaped backslash (\), a carriage return, or a line feed. Special characters can be included in string literals using the following escape sequences –

Escape sequence
Meaning
\0
Null Character
\\
\character
\b
Backspace
\f
Form feed
\n
Newline
\r
Carriage return
\t
Horizontal tab
\v
Vertical tab
\'
Single Quote
\"
Double Quote
\000
Octal number of one to three digits
\xhh...
Hexadecimal number of one or more digits

The following example shows how to use a few string literals

import Cocoa
let stringL = "Hello\tWorld\n\nHello\'Swift\'"
println(stringL)

Result:

Hello     World

Hello'Swift'

Boolean Literals


There are three Boolean literals and they are part of standard Swift keywords

  A value of true representing true.
  A value of false representing false.
A value of nil representing no value.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.