Classification of data in computer science.
In this unit, we will delve into the fundamental building blocks of any Swift program: data types and variables. Understanding these concepts is crucial to becoming proficient in Swift programming.
Swift has several built-in data types. These include:
Integers: These are whole numbers without a fractional component, such as 42 and -23. Swift provides signed and unsigned integers of various sizes.
Floats and Doubles: These are used to represent numbers with a fractional component, such as 3.14159 or 0.1. Float
represents a 32-bit floating-point number and Double
represents a 64-bit floating-point number.
Booleans: This is a simple data type that represents true or false.
Strings: This is a series of characters, such as "hello, world".
Characters: This represents a single character, such as "a".
Variables and constants are used to store information. In Swift, you declare a variable with the var
keyword and a constant with the let
keyword. Here's an example:
var myVariable = 42 let myConstant = 3.14159
In the above example, myVariable
is an integer and myConstant
is a double.
Swift is a type-safe language, which means it encourages you to be clear about the types of values your code can work with. If part of your code expects a String
, type safety prevents you from passing it an Int
by mistake.
Swift also uses type inference. When you don’t specify the type of value you need, Swift uses type inference to work out the appropriate type. For example, if you assign a literal value of 42 to a new constant without saying what type it is, Swift infers that you want the constant to be an Int
, because you have initialized it with a number that looks like an integer.
Swift does not allow implicit type conversion, but you can do explicit type conversion (also known as type casting) as follows:
let integer: Int = 100 let decimal: Double = Double(integer)
You can also define a type alias if you want to refer to an existing type by a name that is contextually more appropriate. Here's an example:
typealias AudioSample = UInt16
In the above example, AudioSample
is defined as an alias for UInt16
.
By the end of this unit, you should have a solid understanding of data types, variables, and constants in Swift. These are fundamental concepts that you will use in every Swift program you write.