Introduction

In this section, we will explore the fundamental building blocks of Swift programming: data types and operators. Understanding these concepts is crucial for writing efficient and error-free code. We will cover:

  1. Basic Data Types
  2. Type Inference
  3. Type Safety
  4. Common Operators

Basic Data Types

Swift provides several built-in data types to store different kinds of information. Here are some of the most commonly used ones:

Integers

  • Int: Represents whole numbers. The size of an Int is platform-dependent (32-bit or 64-bit).
let age: Int = 25

Floating-Point Numbers

  • Double: Represents a 64-bit floating-point number.
  • Float: Represents a 32-bit floating-point number.
let pi: Double = 3.14159
let e: Float = 2.71828

Boolean

  • Bool: Represents a Boolean value (true or false).
let isSwiftFun: Bool = true

Strings

  • String: Represents a sequence of characters.
let greeting: String = "Hello, World!"

Characters

  • Character: Represents a single character.
let letter: Character = "A"

Arrays

  • Array: Represents a collection of values of the same type.
let numbers: [Int] = [1, 2, 3, 4, 5]

Dictionaries

  • Dictionary: Represents a collection of key-value pairs.
let studentGrades: [String: Int] = ["Alice": 90, "Bob": 85]

Type Inference

Swift can automatically infer the type of a variable or constant based on the value assigned to it. This means you don't always have to explicitly specify the type.

let inferredInt = 42 // Swift infers this as Int
let inferredDouble = 3.14 // Swift infers this as Double
let inferredString = "Hello" // Swift infers this as String

Type Safety

Swift is a type-safe language, which means it ensures that variables are used consistently with their declared types. This helps catch errors at compile time.

let number: Int = 10
// number = "Ten" // This will cause a compile-time error

Common Operators

Operators are special symbols or phrases used to check, change, or combine values. Here are some of the most commonly used operators in Swift:

Arithmetic Operators

  • Addition (+): Adds two values.
let sum = 5 + 3 // sum is 8
  • Subtraction (-): Subtracts one value from another.
let difference = 10 - 2 // difference is 8
  • Multiplication (*): Multiplies two values.
let product = 4 * 2 // product is 8
  • Division (/): Divides one value by another.
let quotient = 16 / 2 // quotient is 8
  • Remainder (%): Returns the remainder of a division.
let remainder = 10 % 3 // remainder is 1

Comparison Operators

  • Equal to (==): Checks if two values are equal.
let isEqual = (5 == 5) // isEqual is true
  • Not equal to (!=): Checks if two values are not equal.
let isNotEqual = (5 != 3) // isNotEqual is true
  • Greater than (>): Checks if one value is greater than another.
let isGreater = (5 > 3) // isGreater is true
  • Less than (<): Checks if one value is less than another.
let isLess = (3 < 5) // isLess is true
  • Greater than or equal to (>=): Checks if one value is greater than or equal to another.
let isGreaterOrEqual = (5 >= 5) // isGreaterOrEqual is true
  • Less than or equal to (<=): Checks if one value is less than or equal to another.
let isLessOrEqual = (3 <= 5) // isLessOrEqual is true

Logical Operators

  • Logical AND (&&): Returns true if both operands are true.
let andResult = (true && false) // andResult is false
  • Logical OR (||): Returns true if at least one operand is true.
let orResult = (true || false) // orResult is true
  • Logical NOT (!): Inverts the Boolean value.
let notResult = !true // notResult is false

Practical Exercises

Exercise 1: Basic Arithmetic

Write a Swift program that calculates the sum, difference, product, and quotient of two numbers.

let a = 10
let b = 5

let sum = a + b
let difference = a - b
let product = a * b
let quotient = a / b

print("Sum: \(sum), Difference: \(difference), Product: \(product), Quotient: \(quotient)")

Exercise 2: Type Inference and Safety

Create variables with inferred types and try to assign values of different types to them. Observe the errors.

let inferredInt = 42
// inferredInt = "Forty-two" // This will cause a compile-time error

let inferredString = "Hello"
// inferredString = 123 // This will cause a compile-time error

Exercise 3: Comparison and Logical Operators

Write a Swift program that uses comparison and logical operators to evaluate some conditions.

let x = 10
let y = 20

let isEqual = (x == y)
let isNotEqual = (x != y)
let isGreater = (x > y)
let isLess = (x < y)
let isGreaterOrEqual = (x >= y)
let isLessOrEqual = (x <= y)

let andResult = (x < y) && (x != y)
let orResult = (x > y) || (x == y)
let notResult = !(x == y)

print("isEqual: \(isEqual), isNotEqual: \(isNotEqual), isGreater: \(isGreater), isLess: \(isLess), isGreaterOrEqual: \(isGreaterOrEqual), isLessOrEqual: \(isLessOrEqual)")
print("andResult: \(andResult), orResult: \(orResult), notResult: \(notResult)")

Summary

In this section, we covered the basic data types and operators in Swift. We learned about integers, floating-point numbers, Booleans, strings, characters, arrays, and dictionaries. We also explored type inference and type safety, and we looked at common arithmetic, comparison, and logical operators. By understanding these fundamental concepts, you are now equipped to write more complex and efficient Swift programs. In the next section, we will dive into control flow, which will allow you to make decisions and control the execution of your code.

© Copyright 2024. All rights reserved