Literals and Type Inference in Swift
Literally a great type
A literal allows us to represent values in source code, and the compiler supplies us with a range of types to help us out. Furthermore, Swift helps us by inferring types for us.
This all sounds great, so join me for this deep submerge into the topic.
Difficulty: Beginner | Easy | Normal | Challenging
Terminology
Literal: A representation of a value in source code. An example is the type String in Swift
Type Inference: The automatic detection of data types
Literals
Literals in Swift specify a value rather than a concrete type.
For example, "Hello,World"
is a String literal
type as Swift initializes the default type for that kind of literal.
This can be revealed with the following:
let str = "Hello, World"
type(of: str) // String.Type
however creating a nil literal will mean that the Swift compiler is unable to infer the type.
type(of: nil) // Creates an error