Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

swift
communitycreator

What are the primary data types in Swift?

Wale Moshood

Swift offers a rich collection of built-in and user-defined data types.

There are six basic data types in Swift: string, character, integer, float, double, and boolean. These data types are common in most programming languages. Each data type is discussed below.

String

A String is a data type used to store a collection of characters. So, a series of characters represent a string. Strings are used to represent textual data displayed in an app.

When writing a String, it must be wrapped in quotes to be considered valid. We use the String keyword to create string-type variables. The example below demonstrates how to create a string-type variable.

let text: String = "Hello, world"

print(text)

Output

Hello, world

Integer

Integer, also represented as Int, is a data type used to perform mathematical operations such as addition, subtraction, and multiplication.

Integer is also used to represent whole numbers with no fractional components. We use the Int keyword to create integer-type variables. An example is shown below.

let digit: Int = 5

print(digit)

Depending on the platform type, Swift programming provides different variants of Integer that have different sizes.

Output

5

Character

Characters are used to store a single character string, whether it is a literal, emoji, or a language other than English. If more than one character is assigned to a variable of type Character, an error message is thrown.

We use the Character keyword to create character-type variables. An example is shown below.

let alphabet: Character = "a"

print(alphabet)

Output

a

Float

Float or Floating-point number is a data type used to represent whole numbers with a fractional component. Floats are also used to perform various mathematical operations and store numbers with up to six decimal places.

We use the Float keyword to create float-type variables. An example is shown below.

let sampleFloat: Float = 3.333

print(sampleFloat)

Output

3.333

Double

The Double data type is similar to Float and is used to represent whole numbers with a fractional component. Double differs by storing numbers with up to 15 decimal places.

We use the Double keyword to create double-type variables. An example is shown below.

let sampleDouble: Double = 13.3107967012433

print(sampleDouble)

Output

13.3107967012433

Boolean

boolean or Bool is a data type used to represent logical entities. We use boolean to determine if logic is true or false. Boolean is usually used with if-else statements.

We use the Bool keyword to create boolean-type variables.

let checkPassed: Bool = true

print(checkPassed) 

Output

true

RELATED TAGS

swift
communitycreator
RELATED COURSES

View all Courses

Keep Exploring