Sobes.tech
Intern

What are the types of data in Swift?

sobes.tech AI

Answer from AI

In Swift, the main data types include:

  1. Integer types: Int, UInt, Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64. Int and UInt have sizes depending on the current platform (usually 32 or 64 bits).

  2. Floating-point types: Float (represents a 32-bit floating-point number), Double (represents a 64-bit floating-point number, preferred for most cases).

  3. Boolean type: Bool. Can hold true or false.

  4. String type: String. Contains a sequence of characters.

  5. Character type: Character. Represents a single Unicode character.

  6. Collections:

    • Arrays (Array): An ordered collection of elements of the same type.
    • Sets (Set): An unordered collection of unique elements of the same type.
    • Dictionaries (Dictionary): An unordered collection of key-value pairs, where keys are unique and of one type, and values are of another type.
  7. Optional types (Optional): Represent either a value of a certain type or no value (nil). Denoted by adding ? or ! to the type.

  8. Tuples (Tuple): Allow grouping multiple values into a single compound type. The types of values in a tuple can be different.

  9. Enumerations (Enums): Allow defining a group of related values.

  10. Structures (Struct): Value types. Suitable for modeling data.

  11. Classes (Class): Reference types. Suitable for modeling complex objects and hierarchies.

Examples:

// Int
let age: Int = 30

// Double
let price: Double = 19.99

// Bool
let isAvailable: Bool = true

// String
let name: String = "Alice"

// Array
let numbers: [Int] = [1, 2, 3]

// Dictionary
let person: [String: Any] = ["name": "Bob", "age": 25]

// Optional Int
var optionalInt: Int? = nil

// Tuple
let coordinates = (x: 10, y: 20)

// Enum
enum Status {
    case active
    case inactive
}
let currentStatus: Status = .active

// Struct
struct Point {
    var x: Int
    var y: Int
}
let myPoint = Point(x: 5, y: 10)

// Class
class Person {
    var name: String
    init(name: String) {
        self.name = name
    }
}
let newPerson = Person(name: "Charlie")
What are the types of data in Swift? — iOS - sobes.tech