Swift LiteralsA Literal is the direct value of variable or constant. It may be a number, character or string. Literals are used to initialize or assign value to variables or constants. Example:Here, javatpoint.com is a literal and siteName is a constant. Types of Swift LiteralsInteger Literals
Example of Integer Literal:Output: 255 1231 The above example contains two integer literals 0b11111111 (binary literal) and 1231 (decimal literal). 255 is the decimal value of 11111111 that's why the print(binaryNumber) statement outputs 255 in the screen. String & Character Swift literalsA sequence of characters covered by double quotes is called string literal and a single character covered by double quotes is called character literal. Example:Output: C C is an awesome programming language Floating Point LiteralsFloating point literals are used for float and double values. There are two types of floating point literals: Decimal:It can store an optional exponent, indicated by an uppercase or lowercase e. For decimal numbers with an exponent of exp, the base number is multiplied by 10exp. Example:Output: 3.1416 314.0 Hexadecimal:Hexadecimal floats must contain an exponent, indicated by an uppercase or lowercase p. For hexadecimal numbers with an exponent of exp, the base number is multiplied by 2exp. Example:Output: 15360.0 0.003662109375 Boolean LiteralsThere are two Boolean literals in Swift: true and false. Example:Output: false true Type AliasThe typealias is used to create a new name for an existing type. Syntax:Example:Let's take an example where we put "Raj" as another name for type Int. Output: 100 Type SafetySwift 4 is a type-safe language. If your code requires Int, then you can't use String. It performs type-checks when compiling your code and flags any mismatched types as errors. Example:Output: main.swift:2:8: error: cannot assign value of type 'String' to type 'Int' varA = "Hello World!" ^~~~~~~~~~~~~~ You can see that the above program get a compile time error just because of type safety. Type InferenceSwift is a type inference language means when you compile the Swift code, it automatically check the type of value you provide. It automatically choose the appropriate data type for successful execution. Example:Output: Love is life 143 3.1416 3.1416 Next TopicSwift vs Objective C |