Suraj Kumar Mandal

Basics:

Intermediate:

Advanced:

1. Introduction to Swift

What is Swift?

Swift is a powerful and intuitive programming language developed by Apple for iOS, macOS, watchOS, tvOS, and beyond. It's designed to be fast, safe, and modern, incorporating elements from various programming languages.

Setting Up Swift

To start programming in Swift, you'll need:

Writing Your First Swift Program

Open Xcode and create a new Swift Playground or Project.

In a Playground:

// Hello, World! program in Swift
print("Hello, World!")

In a Project:

import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        // Hello, World! displayed in the console
        print("Hello, World!")
    }
}

Comments in Swift

In Swift, you can use '//' for single-line comments and '/* */' for multi-line comments.

Running Your Code

For a Playground, your code is executed instantly and you can see the output in the sidebar. For a Project, run the app in the simulator or on a physical device.

2. Variables and Constants

Variables

In Swift, variables are declared using 'var' and can be changed after initialization.

var myVariable = 42
myVariable = 50

Constants

Constants are declared using 'let' and cannot be changed after initialization.

let myConstant = 42
// This will cause an error: myConstant = 50

Type Annotations

You can provide type information when declaring variables or constants.

var myString: String = "Hello"
let myInt: Int = 10

Type Inference

Swift can infer the type of a variable or constant based on its initial value.

var inferredString = "Hello" // Swift infers the type as String
let inferredInt = 10 // Swift infers the type as Int

Printing Variables

Use 'print()' to display the value of a variable or constant in the console.

let name = "Alice"
print("Hello, \(name)!") // Output: Hello, Alice!

3. Data Types and Operators

Basic Data Types

Swift provides various built-in data types:

Type Conversion

You can convert between different data types using explicit casting.

let intValue = 42
let doubleValue = Double(intValue) // Converts integer to double
let stringValue = String(intValue) // Converts integer to string

Operators

Swift supports various operators:

let myConstant = 42
// This will cause an error: myConstant = 50

Type Annotations

You can provide type information when declaring variables or constants.

var myString: String = "Hello"
let myInt: Int = 10

Type Inference

Swift can infer the type of a variable or constant based on its initial value.

var inferredString = "Hello" // Swift infers the type as String
let inferredInt = 10 // Swift infers the type as Int

Printing Variables

Use 'print()' to display the value of a variable or constant in the console.

let name = "Alice"
print("Hello, \(name)!") // Output: Hello, Alice!
Scroll to Top