With Swift, you’ll need to use different types of variables to store values and refer to them by an identifying name. This is not unlike most other programming languages. There are a set of basic Swift data types for storing numbers, strings, and Boolean values.
Swift also provides robust versions of the primary collection types Array, Set, and Dictionary. Descriptions for these collection types are in the Swift Collection Data Types section. Swift also introduces some advanced new data types with Optional and Tuples. By convention, Swift data types use camel case notation for their names.
Basic Swift Data Types
Swift 4 offers the programmer a variety of basic data types to use as well as user-defined data types. The following Swift data types are most frequently used when declaring variables:
Int or UInt
Signed and unsigned integers are used to store whole numbers. Swift provides signed and unsigned integers in 8, 16, 32, and 64-bit forms. These integers follow a naming convention that states the bit size and whether it is signed or unsigned. Int8, Int16, Int32, and Int64 are the specific data types for signed integers. UInt8, UInt16, UInt32, and UInt64 are for unsigned integers.
- On a 32-bit platform, Int is the same size as Int32 and UInt is the same size as UInt32.
- On a 64-bit platform, Int is the same size as Int64 and UInt is the same size as UInt64.
// Initialization of signed integers var number: Int = 31 var number: Int8 = -125 var number: Int16 = 31033 var number: Int32 = -35023 var number: Int64 = -9223372036854775808 // Initialization of unsigned integers var number: UInt = 31 var number: UInt8 = 250 var number: UInt16 = 64031 var number: UInt32 = 4254969295 var number: UInt64 = 18446744073709551615
|Int8||1 byte||-127 to 127|
|UInt8||1 byte||0 to 255|
|Int16||2 bytes||-32768 to 32767|
|UInt16||2 bytes||0 to 65535|
|Int32||4 bytes||-2147483648 to 2147483647|
|UInt32||4 bytes||0 to 4294967295|
|Int64||8 bytes||-9223372036854775808 to 9223372036854775807|
|UInt64||8 bytes||0 to 18446744073709551615|
You will need to use floating-point Swift data types when working with decimal numbers. Floating-point types can represent a much wider range of values than integer types and can store numbers that are much larger or smaller than can be stored in an Int. Swift provides two signed floating-point number types. The Swift data types are Float and Double.
To represent a 32-bit floating-point number and numbers with smaller decimal points use Float. However, to represent a 64-bit floating-point number and floating-point values that must be very large, use Double. The Swift compiler always infers a Double type and not a Float when using decimal literal values. Therefore, if you don’t need the precision of a 64-bit value, you should explicitly declare the variable as a Float.
// Float initialization var percent: Float = 10.3 // Double initialization var percent: Double = 10.3 // Inferred as Double var percent = 10.3
|Float||4 bytes||1.2E-38 to 3.4E+38 (~6 digits)|
|Double||8 bytes||2.3E-308 to 1.7E+308 (~15 digits)|
For logical values that can only ever be true or false, there is a basic Boolean Swift data type, called Bool. Swift provides two Boolean constant values, true and false. Boolean values are particularly useful when you work with conditional statements.
// Boolean initialization var skyIsBlue = true
String and Character
Swift’s String and Character data types provide a fast, Unicode-compliant way to work with text in your code. Character is a single-character string literal. For example, “S”. The String type is a series of characters such as “Hello, Swift!”
Every String provides support for accessing those characters in various Unicode representations because they are composed of encoding-independent Unicode characters. String concatenation is as simple as combining two strings with the + operator, and string mutability is managed by choosing between a constant or a variable.
// String initialization var firstName: String = "John" // String type inference var lastName = "Smith" // String concatenation var name = firstName + " " + lastName
Swift Collection Data Types
For storing collections of values, Array, Sets, and Dictionary are three primary collection types provided by Swift. Array, Set, and Dictionary in Swift are always clear about the types of values and keys that they can store. This means that you cannot insert a value of the wrong type into a collection by mistake. It also means you can be confident about the type of values you will retrieve from a collection.
An Array is an ordered list of values that are the same type. When you declare an Array in the Swift programming language, you must specify what type it will contain. After the declaration, it can only contain values of that type. There are two ways to indicate the type of an Array: the long form and the short form. These two ways are equivalent and are interchangeable:
// Array initialization long form var names: Array<String> = ["Stephen", "Jesse", "John", "Clark", "Anna"] // Array initialization short form var names: [String] = ["Stephen", "Jesse", "John", "Clark", "Anna"]
A Set is an unordered collection of unique elements. You use a Set instead of an Array when you need to test efficiently for membership and you aren’t concerned with the order of the elements in the collection, or when you need to ensure that each element appears only once in a collection. Unlike Array, Set does not have a short form.
// Set initialization var names: Set<String> = ["Stephen", "Jesse", "John", "Clark", "Anna"]
Dictionary is an unordered collection of key-value associated items of a specific type. The key acts as an identifier for that value within the Dictionary. Unlike items in an array, Dictionary items do not have a specified order. You use a Dictionary when you need to look up values based on their identifier, similar to using a dictionary to look up the definition of a particular word.
As with Array, there are two ways to indicate the type of a Dictionary: the long form and the short form. The two ways are equivalent and are interchangeable.
// Dictionary initialization long form var grades: Dictionary<String, Int> = ["Clark": 100, "Jesse": 95] // Dictionary initialization short form var grades: [String: Int] = ["Clark": 100, "Jesse": 95]
New Swift Data Types
Apple introduced two new Swift data types that you may not be familiar with. They are Optional and Tuples.
The Optional handles the absence of a value. This Swift data type represents a variable that can hold either a value or no value. You can use an Optional with any data type, not just classes. A good time to use an Optional is when you do not know if the variable you are referencing will contain a value.
There is a long form and a short form when using the Optional type. The shortened form is preferred for ease of reading and writing code.
// Optional initialization long form var number: Optional<Int> = Int("31") // Optional initialization short form var number: Int? = Int("31")
Tuples group multiple values into a single compound value. The values within a tuple can be of any type and don’t have to be of the same type as each other. Tuples enable you to create and pass around groupings of values. Also, you can use a tuple to return multiple values from a function as a single compound value.
There are many ways that you can access the values in a tuple Swift data type. You can decompose a tuple’s contents into separate constants or variables, which you then access as usual. If you only need some of the tuple’s values, ignore parts of the tuple with an underscore (_) when you decompose the tuple. Alternatively, access the individual element values in a tuple using index numbers starting at zero. If you name the elements in a tuple, you can use the element names to access the values of those elements
// Tuple initialize var httpSuccess = (200, "success") // Accessing the Tuple values var (statusCode, statusText) = httpSuccess // Tuple initialize with names var httpSuccess = (statusCode: 200, description: "success") // Accessing the Tuples values by name var statusCode = httpSuccess.statusCode var statusText = httpSuccess.description // Accessing Tuple values using index var statusCode = httpSuccess.0 // Selectively accessing Tuple values var (statusCodeOnly, _) = httpSuccess