Data Types In Swift


Data Types in Swift



Swift is a statically typed language, meaning every variable and constant must have a specific type assigned to it. Here are some commonly used data types in Swift:


 1. Integers (Int):

 Represents whole numbers, both positive and negative.

 Sizes: Int8, Int16, Int32, Int64 (platform-dependent).

 Example: let age: Int = 30


 2. Floating Point Numbers (Float and Double):

 Represents numbers with fractional components.

 Float: 32bit floating-point number.

 Double: 64bit floating-point number, with higher precision than Float.

 Example: 

  swift code

  let pi: Float = 3.14

  let gravity: Double = 9.81

  


 3. Strings (String):

 Represents a sequence of characters.

 Enclosed in double quotes (").

 Example: let name: String = "John"


 4. Booleans (Bool):

 Represents logical values: true or false.

 Used for conditional statements and logical operations.

 Example: let isActive: Bool = true


 5. Optional (Optional<T>):

 Represents a value that may or may not exist.

 Used to handle absence of a value safely.

 Example: var middleName: String? = nil


 6. Tuples:

 Groups multiple values into a single compound value.

 Elements can have different types.

 Example: 

  swift code

  let person: (String, Int) = ("Alice", 25)

  print(person.0) // Output: "Alice"

  print(person.1) // Output: 25

  


 7. Arrays (Array<T>):

 Ordered collection of values of the same type.

 Accessed using index.

 Example: 

  swift code

  var numbers: [Int] = [1, 2, 3, 4, 5]

  print(numbers[0]) // Output: 1

  


 8. Dictionaries (Dictionary<Key, Value>):

 Collection of key-value pairs.

 Keys must be unique within the dictionary.

 Example: 

  swift code

  var scores: [String: Int] = ["John": 95, "Alice": 87]

  print(scores["John"]) // Output: 95

  


 9. Sets (Set<T>):

 Unordered collection of unique values of the same type.

 Example: 

  swift code

  var uniqueNumbers: Set<Int> = [1, 2, 3, 4, 5]

  uniqueNumbers.insert(3) // Duplicate values are ignored

  


 10. Enums (enum):

 Defines a group of related values.

 Example:

  swift code

  enum Direction {

      case north, south, east, west

  }

  let currentDirection: Direction = .north

  


 11. Characters (Character):

 Represents a single Unicode character.

 Enclosed in single quotes (').

 Example: let firstLetter: Character = "A"


Swift's rich set of data types provides flexibility and safety in handling different kinds of data, ensuring efficient and robust code development.

Comments

Popular posts from this blog

Complete iOS Developer Guide - Swift 5 by @hiren_syl |  You Must Have To Know 😎 

Debugging

Swift Fundamentals You Can’t Miss! A List by @hiren_syl