Swift Tutorial

Swift Data Types

Swift Control Flow

Swift Functions

Swift Collections

Swift OOPs

Swift Additional Topics

Swift - Basic Syntax

Swift is a modern programming language developed by Apple for iOS, macOS, watchOS, tvOS, and more. Swift is designed to be fast, safe, and expressive.

Let's go through the basic syntax elements of Swift:

1. Variables and Constants:

Declare a variable using the var keyword and a constant using the let keyword.

var variableName = "This is a variable"
let constantName = "This is a constant"

2. Data Types:

Swift is a statically typed language, which means you should define the data type of a variable when you declare it, but Swift also offers type inference.

var integer: Int = 10
var doubleValue: Double = 10.5
var stringValue: String = "Hello"
var booleanValue: Bool = true

3. Control Flow:

  • If-else statements:

    if booleanValue {
        print("It's true!")
    } else {
        print("It's false!")
    }
    
  • Switch statement:

    switch integer {
    case 1:
        print("One")
    case 2:
        print("Two")
    default:
        print("Other number")
    }
    
  • For-in loops:

    for i in 1...5 {
        print(i)
    }
    

4. Functions:

Functions are declared using the func keyword.

func functionName(parameterName: DataType) -> ReturnType {
    // function body
    return value
}

Example:

func greet(name: String) -> String {
    return "Hello, \(name)!"
}
print(greet(name: "Alice"))  // Outputs: Hello, Alice!

5. Optionals:

Swift introduces the concept of optionals, which handle the absence of a value. Optionals are denoted by a ? after the type.

var optionalString: String? = "This is optional"
optionalString = nil  // This is valid

6. Tuples:

Tuples group multiple values into a single compound value.

let httpStatus = (statusCode: 200, description: "OK")
print(httpStatus.statusCode)  // Outputs: 200

7. Arrays and Dictionaries:

Arrays are ordered collections, and dictionaries are unordered collections of key-value pairs.

var array = [1, 2, 3, 4]
var dictionary = ["key1": "value1", "key2": "value2"]

8. Classes and Structures:

Swift supports object-oriented programming with classes and structures.

class ClassName {
    // class definition
}

struct StructureName {
    // structure definition
}

9. Comments:

Comments in Swift can be single-line using // or multi-line using /* */.

// This is a single-line comment

/*
This is a
multi-line comment
*/

This overview provides just a glimpse of Swift's syntax. Swift has many more features and advanced functionalities, like protocols, extensions, closures, error handling, and much more, that make it a powerful and expressive language.

  1. Declaring and using functions in Swift:

    • Description: Functions in Swift are self-contained blocks of code that perform a specific task. They allow you to organize your code into reusable units, making it easier to read and maintain.

    • Code:

      // Function declaration
      func greet(name: String) -> String {
          return "Hello, \(name)!"
      }
      
      // Function usage
      let greeting = greet(name: "John")
      print(greeting) // Output: "Hello, John!"
      

    In this example, the function greet takes a parameter name of type String and returns a greeting message. The function is then called with the argument "John," and the result is printed.

  2. Introduction to Swift operators and expressions:

    • Description: Swift operators are symbols or keywords that perform operations on variables and values. Expressions are combinations of values and operators that produce a result.

    • Code:

      // Arithmetic operators
      let sum = 5 + 3
      let difference = 7 - 2
      let product = 4 * 6
      let quotient = 10 / 2
      
      // Comparison operators
      let isEqual = sum == difference
      let isGreater = product > quotient
      
      // Logical operators
      let andResult = true && false
      let orResult = true || false
      let notResult = !true
      

    In this example, arithmetic, comparison, and logical operators are used to perform various operations. The results are assigned to variables, demonstrating the use of operators in Swift expressions.