What are the types of data in Swift?
sobes.tech AI
Answer from AI
In Swift, the main data types include:
-
Integer types:
Int,UInt,Int8,UInt8,Int16,UInt16,Int32,UInt32,Int64,UInt64.IntandUInthave sizes depending on the current platform (usually 32 or 64 bits). -
Floating-point types:
Float(represents a 32-bit floating-point number),Double(represents a 64-bit floating-point number, preferred for most cases). -
Boolean type:
Bool. Can holdtrueorfalse. -
String type:
String. Contains a sequence of characters. -
Character type:
Character. Represents a single Unicode character. -
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.
- Arrays (
-
Optional types (
Optional): Represent either a value of a certain type or no value (nil). Denoted by adding?or!to the type. -
Tuples (
Tuple): Allow grouping multiple values into a single compound type. The types of values in a tuple can be different. -
Enumerations (Enums): Allow defining a group of related values.
-
Structures (
Struct): Value types. Suitable for modeling data. -
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")