Literals
- These are values hard coded as such in the code.
print(18) // 18 is an Integer literal
print(3.14) // 3.14 is a Double literal
print("Hello") // "Hello" is a String literal
print(true) // true is a Boolean literal
- Type of the literal is automatically inferred.
- Numeric literals of difference bases
18 // Decimal integer literal
2.5e3 // Decimal double literal. This evaluates to 2.5 x 103
0b1010 // Binary literal has a prefix of 0b
0o1357 // Octal literal has a prefix of 0o
0x15AF // Hex literal has a prefix of 0x
0xABCDEFp5 // Hex literal with exponent. This evaluates to 0xABCDEF x 25
Constants
- The syntax for declaring constants is
let constantName: TypeName = value/object
let message: String = "Hello" // message is an immutable String
let pi = 3.14 // Automatic Type Inference to Double
let a: Int // Despite being a constant (immutable), the value is
// not assigned here. This is possible, provided you
// set the value during initialization, which is
// discussed later.
let a, b, c: Int // All 3 constants are of type Int
let a: Int, b, c: String // "a" is Int, "b" and "c" are Strings
let a = 1, b = 2, c = 3.14 // "a" and "b" are Ints, "c" is a Double
Variables
- The syntax for declaring variables is
var variableName: TypeName = value/object
var message: String = "Hello" // message is a mutable String
var pi = 3.14 // Automatic type inference to Double
var a: Int
var a, b, c: Int
var a: Int, b, c: String
var a = 1, b = 2, c = 3.14
Naming Constants & Variables
-
Almost any character (including Unicode) can be used for names.
-
Can not use math symbols, box drawing characters, arrows etc.
-
Can not begin with numbers.
Commenting Code
print("Hello World!") // This is a comment
/*
print("Hello")
print("World")
*/
/*
print("Hello")
/*
print("World") // Some comment
*/
*/
Semicolon