Category: Swift

  • Swift Data Types

    In any programming language, data types are crucial for determining the type of data stored in a variable. In Swift, variables are used to store data, and their type determines what kind of data they hold. This helps the operating system allocate appropriate memory and ensures that only the correct type of data is stored. For instance, an integer variable can only hold integer values, not strings. Swift supports the following primary data types:
    Int, String, Float, Double, Bool, and Character.

    Integer and Floating-Point Numbers

    Integers are whole numbers that can be positive, negative, or zero. They do not contain fractional components. In programming, integers are classified as:

    • Unsigned integers (UInt): Zero or positive numbers.
    • Signed integers (Int): Can include negative numbers.

    Swift provides integers in various bit sizes: 8-bit, 16-bit, 32-bit, and 64-bit. The naming convention follows a pattern similar to C. For example:

    • A signed 16-bit integer is represented as Int16.
    • An unsigned 8-bit integer is represented as UInt8.
    Integer Bounds

    The following table shows the minimum and maximum values for each integer type:

    Integer TypeMinMax
    UInt80255
    UInt16065,535
    UInt3204,294,967,295
    UInt64018,446,744,073,709,551,615
    Int8-128127
    Int16-32,76832,767
    Int32-2,147,483,6482,147,483,647
    Int64-9,223,372,036,854,775,8089,223,372,036,854,775,807

    Swift also provides two additional types:

    • Int: Platform-native integer, equivalent to Int32 on 32-bit platforms and Int64 on 64-bit platforms.
    • UInt: Platform-native unsigned integer, similar to UInt32 or UInt64 depending on the platform.
    Finding Minimum and Maximum Values

    Swift allows us to find the bounds of integer types using the .min and .max properties. Here’s an example:

    Example:

    print("Integer Type        Min                    Max")
    print("UInt8           \(UInt8.min)         \(UInt8.max)")
    print("UInt16          \(UInt16.min)        \(UInt16.max)")
    print("UInt32          \(UInt32.min)        \(UInt32.max)")
    print("UInt64          \(UInt64.min)        \(UInt64.max)")
    print("Int8            \(Int8.min)          \(Int8.max)")
    print("Int16           \(Int16.min)         \(Int16.max)")
    print("Int32           \(Int32.min)         \(Int32.max)")
    print("Int64           \(Int64.min)         \(Int64.max)")

    Output:

    Integer Type        Min                    Max
    UInt8               0                     255
    UInt16              0                     65535
    UInt32              0                     4294967295
    UInt64              0                     18446744073709551615
    Int8               -128                   127
    Int16              -32768                 32767
    Int32              -2147483648            2147483647
    Int64              -9223372036854775808   9223372036854775807
    Floating-Point Numbers

    Floating-point numbers can represent both integers and numbers with fractional components. Swift provides two types of floating-point numbers:

    TypeBit SizeDecimal Precision
    Double64-bitUp to 15 decimal places
    Float32-bitUp to 6 decimal places

    These numbers can represent values like: 5.670.012345.6789, etc.

    Examples

    // Using Double
    var largeDecimal: Double = 12345.6789012345
    print("Double value is:", largeDecimal)
    
    // Using Float
    var smallDecimal: Float = 5.6789
    print("Float value is:", smallDecimal)

    Output:

    Double value is: 12345.6789012345
    Float value is: 5.6789

    Strings in Swift

    Strings in Swift are collections of characters. For example, "Hello, World!" is a string. Swift strings are Unicode-compliant and case-insensitive. They are encoded using UTF-8, which defines how Unicode data is stored in bytes.

    In Swift, strings are a fundamental data type and are often implemented as an array of characters. They can also represent more general collections or sequences of data elements.

    Creating a String

    Strings in Swift can be created using string literals, the String keyword, or the String initializer.

    Syntax:

    var str: String = "Hello, Swift!"
    var str2 = "Swift Programming"

    Examples:

    // String creation using string literal
    var greeting = "Welcome to Swift Programming"
    print(greeting)
    
    // String creation using String instance
    var message = String("This is an example")
    print(message)
    
    // String creation using String keyword
    var note: String = "Enjoy Coding"
    print(note)

    Output:

    Welcome to Swift Programming
    This is an example
    Enjoy Coding
    Multi-Line String

    A multi-line string spans multiple lines and is enclosed in triple double quotes.

    Syntax:

    """
    This is a
    multi-line string
    example in Swift.
    """

    Example:

    let multilineString = """
    Swift strings are versatile.
    You can create multi-line strings
    easily with triple quotes.
    """
    
    print(multilineString)

    Output:

    Swift strings are versatile.
    You can create multi-line strings
    easily with triple quotes.
    Empty String

    An empty string is a string with no characters. You can create an empty string using either "" or the String() initializer.

    Syntax:

    var emptyStr = ""
    var anotherEmptyStr = String()

    Example:

    var empty = ""
    if empty.isEmpty {
        print("The string is empty.")
    }
    
    let anotherEmpty = String()
    if anotherEmpty.isEmpty {
        print("This is also an empty string.")
    }

    Output:

    The string is empty.
    This is also an empty string.
    String Concatenation

    Strings can be concatenated using various methods:

    1. Addition Operator (+):

    var result = str1 + str2

    2. Addition Assignment Operator (+=):

    result += str2

    3. Append Method:

    str1.append(str2)

    Example:

    let part1 = "Swift "
    let part2 = "is powerful."
    
    // Using +
    var sentence = part1 + part2
    print(sentence)
    
    // Using +=
    var phrase = "Learning "
    phrase += "Swift is fun."
    print(phrase)
    
    // Using append()
    var text = "Hello"
    text.append(", Swift!")
    print(text)

    Output:

    Swift is powerful.
    Learning Swift is fun.
    Hello, Swift!
    String Comparison

    Strings can be compared using the == (equal to) or != (not equal to) operators.

    Syntax:

    string1 == string2
    string1 != string2

    Example:

    let stringA = "Swift Programming"
    let stringB = "Learning Swift"
    
    if stringA == stringB {
        print("The strings are equal.")
    } else {
        print("The strings are not equal.")
    }

    Output:

    The strings are not equal.
    String Length

    The length of a string can be determined using the count property.

    Example:

    let text = "Swift Language"
    print("The length of '\(text)' is \(text.count).")

    Output:

    The length of 'Swift Language' is 14.
    String Interpolation

    String interpolation allows mixing variables, constants, and expressions into a string.

    Syntax:

    let str = "Swift \(version)"

    Example:

    let value = 42
    let multiplier = 2
    print("The result of \(value) times \(multiplier) is \(value * multiplier).")

    Output:

    The result of 42 times 2 is 84.
    String Iteration

    Strings can be iterated over using a for-in loop.

    Example:

    for char in "Swift" {
        print(char, terminator: " ")
    }

    Output:

    S w i f t
    Common String Functions and Properties
    NameDescription
    isEmptyChecks if the string is empty.
    hasPrefixChecks if the string starts with the specified prefix.
    hasSuffixChecks if the string ends with the specified suffix.
    countReturns the length of the string.
    utf8Returns the UTF-8 representation of the string.
    insert(_:at:)Inserts a value at a specified position.
    remove(at:)Removes a value at a specified position.
    reversed()Returns the reversed string.

    Example:

    let sample = "Swift Language"
    
    // Using isEmpty
    print("Is string empty? \(sample.isEmpty)")
    
    // Using hasPrefix
    print("Does string start with 'Swift'? \(sample.hasPrefix("Swift"))")
    
    // Using reversed()
    print("Reversed string: \(String(sample.reversed()))")

    Output:

    Is string empty? false
    Does string start with 'Swift'? true
    Reversed string: egaugnaL tfiwS

    String Functions and Operators in Swift

    A string is a sequence of characters that can either be a literal constant or a variable. For example, "Hello World" is a string of characters. Swift strings are Unicode-correct and locale-insensitive. They support various operations like comparison, concatenation, iteration, and more.

    Creating Strings in Swift

    You can create strings in Swift using either a String instance or a string literal.

    1. Using String() Initializer: The String() initializer creates a string instance.

    Syntax:

    var str = String("Example String")

    Example:

    // Using String() initializer
    var greeting = String("Welcome to Swift!")
    print(greeting)

    Output:

    Welcome to Swift!

    2. Using String Literal: Double quotes are used to create string literals, similar to other programming languages.

    Syntax:

    var str = "Hello"
    var strTyped: String = "World"

    Examples:

    // Creating strings using literals
    var message = "Learning Swift is fun!"
    print(message)
    
    var typedMessage: String = "Swift Programming"
    print(typedMessage)

    Output:

    Learning Swift is fun!
    Swift Programming
    Multi-line Strings 

    Swift supports multi-line strings using triple double quotes (""").

    Syntax:

    Learning Swift is fun!
    Swift Programming

    Examples:

    // Multi-line string example
    let paragraph = """
    Welcome to Swift!
    This example demonstrates
    multi-line strings.
    """
    print(paragraph)

    Output:

    Welcome to Swift!
    This example demonstrates
    multi-line strings.
    String Properties and Functions

    Empty String: An empty string has no characters and a length of zero.

    Example:

    // Creating an empty string
    var emptyLiteral = ""
    var emptyInstance = String()
    
    print("Is emptyLiteral empty? \(emptyLiteral.isEmpty)")
    print("Is emptyInstance empty? \(emptyInstance.isEmpty)")

    Output:

    Is emptyLiteral empty? true
    Is emptyInstance empty? true

    String Length: The count property returns the total number of characters in a string.

    Example:

    // Counting characters in a string
    let text = "Swift Programming"
    let length = text.count
    print("The length of the text is \(length)")

    Output:

    The length of the text is 18
    String Operations

    1. Concatenation: The + operator concatenates strings.

    Example:

    // Concatenating strings
    let firstName = "John"
    let lastName = "Doe"
    let fullName = firstName + " " + lastName
    print("Full Name: \(fullName)")

    Output:

    Full Name: John Doe

    2. Comparison: Use == to check equality and != to check inequality.

    Example:

    let a = "Swift"
    let b = "Swift"
    let c = "Python"
    
    // Equality
    print(a == b)  // true
    
    // Inequality
    print(a != c)  // true

    Output:

    true
    true
    String Functions:

    1. hasPrefix and hasSuffix: Check if a string starts or ends with a specific substring.

    Example:

    let sentence = "Learning Swift"
    print(sentence.hasPrefix("Learn"))  // true
    print(sentence.hasSuffix("Swift")) // true

    Output:

    true
    true

    2. lowercased() and uppercased(): Convert all characters in a string to lowercase or uppercase.

    Example:

    let text = "Swift Programming"
    print(text.lowercased())  // "swift programming"
    print(text.uppercased())  // "SWIFT PROGRAMMING"

    Output:

    swift programming
    SWIFT PROGRAMMING

    3. reversed(): Reverse the characters of a string.

    Example:

    let word = "Swift"
    let reversedWord = String(word.reversed())
    print("Original: \(word)")
    print("Reversed: \(reversedWord)")

    Output:

    Original: Swift
    Reversed: tfiwS

    4. insert(_:at:): Insert a character at a specified position.

    Example:

    var phrase = "Swift Programming"
    phrase.insert("!", at: phrase.endIndex)
    print(phrase)

    Output:

    Swift Programming!

    5. remove(at:): Remove a character at a specific index.

    Example:

    var text = "Hello Swift!"
    let index = text.index(text.startIndex, offsetBy: 6)
    let removedCharacter = text.remove(at: index)
    print("Modified text: \(text)")
    print("Removed character: \(removedCharacter)")

    Output:

    Modified text: Hello Sift!
    Removed character: w

    Data Type Conversions in Swift

    Type Conversion in Swift

    Type Conversion refers to the process of converting a variable or value from one data type to another. This allows instances to be checked and cast to specific class types. In Swift, type conversion is often performed during compile-time by the XCode compiler, provided the data types are compatible (e.g., integer, string, float, double).

    Type conversion involves explicitly casting a value to a different data type using the desired type as a function. For instance:

    var stringToFloatNum: Float = Float(67891)!

    Syntax:

    var <variable_name>: <data_type> = <convert_data_type>(<value>)

    1. Convert Integer to String: This program converts an integer value to a string and displays the result with its type.

    Example:

    import Swift
    
    var intNumber: Int = 789
    
    var intNumberToString: String = String(intNumber)
    
    print("Integer Value = \(intNumber) of type \(type(of: intNumber))")
    print("String Value = \(intNumberToString) of type \(type(of: intNumberToString))")

    Output:

    Integer Value = 789 of type Int
    String Value = 789 of type String

    2. Convert String to Integer: This program converts a string value to an integer and displays the result with its type.

    Example:

    import Swift
    
    var intNum: Int = 789
    
    var intNumToFloat: Float = Float(intNum)
    
    print("Integer Value = \(intNum) of type \(type(of: intNum))")
    print("Float Value = \(intNumToFloat) of type \(type(of: intNumToFloat))")

    Output:

    String Value = 789 of type String
    Integer Value = 789 of type Int

    3. Convert String to Integer: This program converts a string value to an integer and displays the result with its type.

    Example:

    import Swift
    
    var string: String = "789"
    
    var stringToInt: Int = Int(string)!
    
    print("String Value = \(string) of type \(type(of: string))")
    print("Integer Value = \(stringToInt) of type \(type(of: stringToInt))")

    Output:

    String Value = 789 of type String
    Integer Value = 789 of type Int

    4. Convert Integer to Float: This program converts an integer value to a float and displays the result with its type.

    Example:

    import Swift
    
    var intNum: Int = 789
    
    var intNumToFloat: Float = Float(intNum)
    
    print("Integer Value = \(intNum) of type \(type(of: intNum))")
    print("Float Value = \(intNumToFloat) of type \(type(of: intNumToFloat))")

    Output:

    Integer Value = 789 of type Int
    Float Value = 789.0 of type Float

    5. Convert Float to Integer: This program converts a float value to an integer and displays the result with its type.

    Example:

    import Swift
    
    var floatNum: Float = 789.0089
    
    var floatNumToInt: Int = Int(floatNum)
    
    print("Float Value = \(floatNum) of type \(type(of: floatNum))")
    print("Integer Value = \(floatNumToInt) of type \(type(of: floatNumToInt))")

    Output:

    Float Value = 789.0089 of type Float
    Integer Value = 789 of type Int

    6. Convert String to Float: This program converts a string value to a float and displays the result with its type.

    Example:

    import Swift
    
    var string: String = "789"
    
    var stringToFloatNum: Float = Float(string)!
    
    print("String Value = \(string) of type \(type(of: string))")
    print("Float Value = \(stringToFloatNum) of type \(type(of: stringToFloatNum))")

    Output:

    String Value = 789 of type String
    Float Value = 789.0 of type Float

    Convert String to Int Swift

    In Swift, you can convert a string into an integer using various methods. However, only numeric strings can be successfully converted to integers. Below are two common methods to perform this conversion.

    Declaring a String Variable

    A string in Swift is a collection of characters and can be declared using the String data type.

    Syntax:

    let myVariable: String

    Example:

    let myVariable = "Hello"
    Methods for String to Integer Conversion

    1. Using Int Initializer Swift provides an initializer function for integers that can convert a string to an Int. This initializer returns an optional integer. To handle non-numeric strings, you can use the nil-coalescing operator to provide a default value, such as 0.

    Example:

    // Converting a numeric string
    let myStringVariable = "25"
    let myIntegerVariable = Int(myStringVariable) ?? 0
    print("Integer Value:", myIntegerVariable)
    
    // Converting a non-numeric string
    let myStringVariable2 = "Hello"
    let myIntegerVariable2 = Int(myStringVariable2) ?? 0
    print("Integer Value:", myIntegerVariable2)

    Output:

    Integer Value: 25
    Integer Value: 0

    2. Using NSString:The NSString class in Swift allows strings to be passed by reference and includes the integerValue property, which can be used to convert an NSString to an integer.

    Example:

    import Foundation
    
    let myString = "25"
    
    // Converting a string to NSString and then to an integer using integerValue
    let myIntegerVariable = (myString as NSString).integerValue
    print("Integer Value:", myIntegerVariable)

    Output:

    Integer Value: 25
  • Swift Overview

    Swift is a powerful and intuitive programming language developed by Apple Inc. for iOS, macOS, watchOS, and tvOS app development. It was first released in 2014 and has quickly gained popularity due to its simplicity, safety, and performance.

    Key Features
    • Open Source: Swift is open-source, allowing developers to contribute and use it on a wide range of platforms.
    • Safety: Swift is designed with safety in mind, with features like optionals that help prevent null pointer errors.
    • Performance: Swift is optimized for performance, often outperforming Objective-C in various tasks.
    • Modern Syntax: Swift’s syntax is clean and concise, making it easier to read and write.

    Swift Basic Syntax

    Swift’s syntax is designed to be concise and expressive. Below are some basic syntax elements of Swift:

    Hello, World! Example

    Here’s a simple “Hello, World!” program in Swift:

    print("Hello, World!")

    Identifiers

    Identifiers are names used to identify variables, functions, or other user-defined items. They must begin with an alphabet (A-Z or a-z) or an underscore (_) and may contain letters, underscores, and digits. Swift is case-sensitive, so A and a are treated as distinct. Special characters like @#, and % are not allowed in identifiers.

    Examples:

    a, _temp, Temp, a_bc, a29b, temp12, temp_11

    To use a reserved word as an identifier, enclose it in backticks (`).
    Example:

    `exampleIdentifier`

    Keywords

    Keywords are reserved words with predefined meanings in Swift. They cannot be used as variable names or identifiers.

    Examples of Keywords:

    class, func, let, public, struct, return, for, while, if, else, true, false

    Every programming language has a set of reserved words used for internal processes or predefined actions. These reserved words, known as keywords, cannot be used as variable names, constant names, or other identifiers. To use a keyword as an identifier, enclose it in backticks (). For instance, while structis a keyword, “struct“ is a valid identifier. Note that backticks do not change the case sensitivity of identifiers (e.g.,aanda` are treated the same).

    In Swift, keywords are categorized into the following groups:

    1. Keywords in declaration
    2. Keywords in statements
    3. Keywords in expressions and types
    4. Keywords in specific contexts
    5. Keywords starting with the number sign (#)
    6. Keywords used in patterns (_)

    1. Keywords Used in Declarations: Keywords used in declarations include:

    associatedtype, class, deinit, enum, extension, fileprivate, func, import,
    init, inout, internal, let, open, operator, private, precedencegroup,
    protocol, public, rethrows, static, struct, subscript, typealias, var

    Example:

    import Swift
    
    // Creating a structure using the `struct` keyword
    struct Employee {
        var name = "John"
        var id = 1234
    }
    
    // Creating an instance of the structure
    var instance = Employee()
    
    // Accessing properties of the structure
    print("Employee Name:", instance.name)
    print("Employee ID:", instance.id)

    Output:

    Employee Name: John
    Employee ID: 1234

    2. Keywords Used in Statements: Keywords used in statements include:

    break, case, catch, continue, default, defer, do, else, fallthrough, for,
    guard, if, in, repeat, return, throw, switch, where, while

    Example:

    import Swift
    
    // Finding the age group
    let age = 70
    
    if age >= 60 {
        print("Senior Citizen")
    } else if age >= 40 {
        print("Middle-aged")
    } else {
        print("Young")
    }

    Output:

    Senior Citizen

    3. Keywords Used in Expressions and Types: Keywords in expressions and types include:

    Any, as, catch, false, is, nil, rethrows, self, Self, super, throw, throws,
    true, try

    Example:

    import Swift
    
    // Creating a class
    class Person {
        func name() {
            print("Hello! My name is Alice")
        }
    }
    
    // Creating a subclass
    class Employee: Person {
        override func name() {
            // Accessing the parent class method using `super`
            super.name()
            print("I work in the IT department")
        }
    }
    
    // Creating an instance of the subclass
    let employee = Employee()
    employee.name()

    Output:

    Hello! My name is Alice
    I work in the IT department

    4. Keywords Used in Specific Contexts: Keywords used in specific contexts include:

    associativity, convenience, didSet, dynamic, final, get, indirect, infix,
    lazy, left, mutating, none, nonmutating, optional, override, postfix,
    precedence, prefix, Protocol, required, right, set, some, Type, unowned,
    weak, willSet

    Example:

    import Swift
    
    // Creating a structure
    struct Data {
        var value: String
    
        // Using the `mutating` keyword
        mutating func updateValue() {
            self.value = "Updated Value"
        }
    }
    
    var data = Data(value: "Initial Value")
    data.updateValue()
    print(data.value)

    Output:

    Updated Value

    5. Keywords Starting with the Number Sign (#): Keywords starting with # include:

    #available, #colorLiteral, #column, #dsohandle, #elseif, #else, #endif,
    #error, #fileID, #fileLiteral, #filePath, #file, #function, #if,
    #imageLiteral, #keyPath, #line, #selector, #sourceLocation, #warning

    Example:

    import Swift
    
    // Using `#function` to display the function name
    func displayFunctionName() {
        print("You are in the function: \(#function)")
    }
    
    displayFunctionName()

    Output:

    You are in the function: displayFunctionName

    6. Keywords Used in Patterns (_): The underscore (_) is used as a wildcard in patterns.

    Example:

    import Swift
    
    // Printing a message 10 times
    for _ in 1...10 {
        print("Swift Programming")
    }

    Output:

    Swift Programming
    Swift Programming
    Swift Programming
    Swift Programming
    Swift Programming
    Swift Programming
    Swift Programming
    Swift Programming
    Swift Programming
    Swift Programming

    Semicolons (;)

    Semicolons are optional in Swift but are required when writing multiple statements on the same line.

    Examples:

    var a = 1; var b = 2
    print(a); print(b)

    Output:

    1
    2

    Whitespaces

    Whitespace separates elements in code and improves readability. It is mandatory between keywords and identifiers but optional elsewhere.

    Examples:

    var a = 1
    var b=2 // Valid but less readable
    var c = a + b // Preferred for readability

    Literals

    Literals represent fixed values in a program, such as integers, decimals, strings, or booleans. These values can be directly used without computation. By default, literals in Swift don’t have a type. Primitive type variables can be assigned literals. For instance:

    • 12 is an integer literal.
    • 3.123 is a floating-point literal.
    • “Swift” is a string literal.
    • true is a boolean literal.
    Swift Protocols for Literals

    Literals must conform to specific protocols depending on their type:

    • ExpressibleByIntegerLiteral: For integer literals.
    • ExpressibleByFloatLiteral: For floating-point literals.
    • ExpressibleByStringLiteral: For string literals.
    • ExpressibleByBooleanLiteral: For boolean literals.

    Example:

    let number: Int32 = 25
    Types of Literals in Swift

    1. Integer Literals: Used to represent whole numbers. If no alternate base is specified, they default to base-10 (decimal). Negative integers are represented using a minus sign (-).

    Examples:

    let positiveNumber = 25
    let negativeNumber = -25
    let numberWithUnderscore = 2_500 // Same as 2500

    Alternate Representations:

    • Binary: Prefix with 0b
    • Octal: Prefix with 0o
    • Hexadecimal: Prefix with 0x

    Example

    let decimalNumber = 10
    let binaryNumber = 0b1010
    let octalNumber = 0o12
    let hexadecimalNumber = 0xA
    
    print("Decimal Number:", decimalNumber)
    print("Binary Number:", binaryNumber)
    print("Octal Number:", octalNumber)
    print("Hexadecimal Number:", hexadecimalNumber)

    Comments make code more understandable. They are ignored by the compiler.

    Single-line comment syntax:

    Decimal Number: 10
    Binary Number: 10
    Octal Number: 10
    Hexadecimal Number: 10

    2. Floating-Point Literals: Represent numbers with a decimal point. The default type is Double. You can explicitly specify the type as Float.

    Examples:

    let number: Int32 = 25

    Exponential Representation:

    let scientificNumber1 = 1.25e3 // 1250
    let scientificNumber2 = 1.25e-3 // 0.00125

    Hexadecimal Floating-Point:

    • Prefix: 0x
    • Exponent: p
    let hexFloat1 = 0xFp1 // 30.0
    let hexFloat2 = 0xFp-1 // 7.5

    Example:

    let decimalFloatingNumber = 0.123
    let scientificNotation = 1.23e2
    let hexFloat = 0xFp1
    
    print("Decimal Floating-Point:", decimalFloatingNumber)
    print("Scientific Notation:", scientificNotation)
    print("Hexadecimal Floating-Point:", hexFloat)

    Output:

    \Decimal Floating-Point: 0.123
    Scientific Notation: 123.0
    Hexadecimal Floating-Point: 30.0

    3. String Literals: Represent a sequence of characters enclosed in double quotes. Strings can be multi-line, escape special characters, or use interpolation.

    • Single-Line String:
    let message = "Hello, World!"
    • Multi-Line String:
    vlet multilineString = """
    This is a
    multi-line string.
    """
    • Escape Sequences:
    let escapedString = "Hello,\nWorld!"
    • String Interpolation:
    let name = "Swift"
    let greeting = "Welcome to \(name) programming!"

    Example:

    let singleLine = "Learning Swift"
    let multiLine = """
    Multi-line
    String Example
    """
    let interpolated = "The value is \(42)"
    
    print(singleLine)
    print(multiLine)
    print(interpolated)

    Output:

    Learning Swift
    Multi-line
    String Example
    The value is 42

    4. Boolean Literals: Boolean literals can be true or false. The default type is Bool.

    Examples:

    let value1 = true
    let value2 = false
    
    print("Value 1:", value1)
    print("Value 2:", value2)

    Output:

    Value 1: true
    Value 2: false

    Comments

    Comments make code more understandable. They are ignored by the compiler.

    Single-line comment syntax:

    // This is a single-line comment

    Multi-line comment syntax:

    /*
    This is a
    multi-line comment
    */

    Print Statement

    The print function displays text, variables, or expressions on the screen.

    Examples:

    print("Hello Swift") // Prints: Hello Swift
    
    var x = 10
    print(x) // Prints: 10
    
    print(5 + 3) // Prints: 8

    Output:

    Hello Swift
    10
    8

    Import Class

    The import keyword brings definitions from another module into the current program.

    Syntax:

    import module

    Examples:

    import Swift
    print("Welcome to Swift Programming")

    Output:

    Welcome to Swift Programming

    Variables and Constants

    Constants and variables in Swift are used to store data with specific types, such as numbers, characters, or strings. A constant cannot be changed after it has been assigned a value, whereas a variable can be modified during the program execution.

    Declaring Constants & Variables in Swift

    Constants and variables must be declared within their scope before being used. The let keyword is used for constants, and the var keyword is used for variables. Swift does not require semicolons (;) to terminate statements.

    let temperature = 20 // Declaring a constant
    var count = 0        // Declaring a variable

    You can declare multiple constants or variables in a single line, separated by commas:

    let x = 10, y = 20, z = 30 // Multiple constants
    var p = 1, q = 2, r = 3    // Multiple variables
    Type Annotation

    Type annotation explicitly specifies the type of a constant or variable at the time of declaration. For example:

    var name: String // Declares a string variable without initialization
    var age: Int     // Declares an integer variable

    If multiple constants or variables are of the same type, you can declare them in one line:

    var firstName, lastName, city: String
    Naming Constants & Variables

    Names can contain any character except mathematical symbols, private Unicode scalar values, arrows, or whitespace characters:

    let pi = 3.14159
    print("Value of pi: \(pi)")
    Printing Constants & Variables

    print() Function

    The print(_:separator:terminator:) function is used to display the value of constants or variables.

    Example:

    let country = "India"
    print(country)

    Output:

    India

    String Interpolation: String interpolation allows embedding constants or variables directly within a string, replacing placeholders with actual values.

    Example:

    var city = "Delhi"
    print("I live in \(city)")

    Output:

    I live in Delhi
  • Swift Tutorial Roadmap

    Introduction to Swift

    Overview of Swift

    Swift is a powerful, modern, and safe programming language developed by Apple for building applications on iOS, macOS, watchOS, and tvOS. It is designed to be fast, expressive, and beginner-friendly while offering high performance for production apps.


    Swift Basic Syntax

    Identifiers and Keywords

    • Swift identifiers and naming conventions
    • Reserved keywords and their usage

    Semicolons and Whitespaces

    • Use of semicolons (;) in Swift
    • Importance of whitespaces in Swift syntax

    Literals

    • Integer literals
    • Floating-point literals
    • String literals
    • Boolean literals

    Comments

    • Single-line comments
    • Multi-line comments

    Print Statement

    • Using print() to display output

    Import Statements

    • Importing frameworks and modules

    Variables and Constants

    Declaring Variables and Constants

    • Using var for variables
    • Using let for constants

    Data Types

    • Type inference in Swift
    • Explicit type annotations

    Numeric Types

    • Integers
    • Floating-point numbers

    Strings in Swift

    String Basics

    • Creating and initializing strings

    String Functions

    • Common string manipulation methods

    Operators in Swift

    Types of Operators

    • Arithmetic operators
    • Comparison operators
    • Logical operators
    • Assignment operators

    Data Type Conversions in Swift

    Type Conversion

    • Converting between different data types

    String to Int Conversion

    • Safely converting String to Int

    Control Flow

    Decision-Making Statements

    • if statement
    • if-else statement
    • if-else-if ladder
    • Nested if-else
    • switch statement

    Loops

    Looping Statements

    • for-in loop
    • while loop
    • repeat-while loop

    Break Statement

    • Using break to exit loops

    Swift Functions

    Functions Overview

    • Defining and calling functions

    Parameters and Return Values

    • Function parameters
    • Returning values from functions

    In-Out Parameters

    • Modifying parameters using inout

    Nested Functions

    • Functions defined inside other functions

    Function Overloading

    • Multiple functions with the same name

    Closures in Swift

    Closures Overview

    • Introduction to closures and their syntax

    Escaping and Non-Escaping Closures

    • Understanding closure lifetimes and memory behavior

    Swift Sets

    Introduction to Sets

    • Creating and using sets

    Set Operations

    • Removing the first element
    • Using removeAll()
    • Checking if an element exists
    • Counting elements
    • Sorting a set
    • Checking if a set is empty
    • Shuffling set elements

    Sets vs Arrays

    • Differences and appropriate use cases

    Swift Arrays

    Arrays Overview

    • Creating and initializing arrays

    Array Properties

    • Count and capacity

    Common Array Operations

    • Removing the first element
    • Counting elements
    • Reversing arrays
    • Using joined()
    • Checking if an array contains an element
    • Sorting arrays
    • Swapping elements
    • Checking if an array is empty

    Swift Dictionary

    Dictionary Basics

    • Creating dictionaries
    • Creating empty dictionaries

    Dictionary Operations

    • Changing values
    • Accessing elements
    • Iterating over dictionaries

    Advanced Dictionary Usage

    • Creating a dictionary from two arrays
    • Removing items
    • Converting dictionaries to arrays

    Dictionary Properties

    • Common dictionary properties

    Swift Tuples

    Tuples in Swift

    • Creating and using tuples

    Swift Object-Oriented Programming (OOP)

    Structures in Swift

    • Creating and using structures

    Properties

    • Stored properties
    • Computed properties

    Methods

    • Instance methods
    • Type methods

    Function vs Method

    • Key differences

    Deinitialization

    • Understanding deinitializers

    Typecasting in Swift

    Typecasting

    • Checking types at runtime
    • Upcasting and downcasting

    Timers in Swift

    Repeating Timers

    • Implementing repeating timers

    Non-Repeating Timers

    • Creating one-time timers

    Swift Error Handling

    Errors in Swift

    • Error handling fundamentals

    try, try?, and try!

    • Differences and when to use each

    Additional Swift Topics

    Typealias

    • Creating and using type aliases

    Swift Structures vs C Structures

    • Key differences

    Swift Interview Preparation

    Interview Questions

    • Theoretical questions
    • Advanced coding challenges
    • Scenario-based questions

    Swift Project Ideas

    Project Ideas

    • Beginner-level Swift projects
    • Intermediate and advanced Swift project ideas