Enums, structures, closures in Swift

Ferdous Mahmud Akash

Ferdous Mahmud Akash

· 2 min read
Enums, structures, closures in Swift

Enums

An enum, short for enumeration, is a type that represents a set of related values. Enums are used to group related values together and make your code more expressive and readable.

In Swift, you can define an enum using the `enum` keyword, followed by the name of the enum and the cases it represents. Here's an example:

enum CompassPoint {
    case north
    case south
    case east
    case west
}

This defines an enum called `CompassPoint` with four cases: north, south, east, and west. You can use this enum to represent directions in your code, like this:

var direction = CompassPoint.north

Structures

A structure, or struct, is a type that groups together related data. Structs are similar to classes, but they are value types rather than reference types. This means that when you assign a struct to a variable or pass it as a parameter to a function, a copy of the struct is made.

In Swift, you can define a struct using the `struct` keyword, followed by the name of the struct and the properties it contains. Here's an example:

struct Person {
    var name: String
    var age: Int
}

This defines a struct called Person with two properties: name and age. You can create a new instance of this struct like this:

var person = Person(name: "Ferdous", age: 22)

Closures

A closure is a block of code that can be passed around and executed at a later time. Closures are similar to functions, but they can be defined inline and they capture the context in which they are defined. This means that they can access and modify variables that are in scope when they are created.

In Swift, you can define a closure using curly braces {}. Here's an example:

let numbers = [1, 2, 3, 4, 5]
let squaredNumbers = numbers.map { $0 * $0 }

This defines a closure that multiplies a number by itself `($0 * $0)`. The closure is then passed to the map method of an array, which applies the closure to each element of the array and returns a new array with the results. In this example, `squaredNumbers` will be [1, 4, 9, 16, 25].

So don't hesitate to start experimenting with enums, structures, and closures in your own projects, and see how they can help you build better software. Happy coding!

Ferdous Mahmud Akash

About Ferdous Mahmud Akash

Hey there! I'm a self-taught iOS developer from Bangladesh.

I'm also passionate about sharing my knowledge and experience with other aspiring developers through my blog at ferdousmahmud.co

Thank you for visiting my website, and feel free to reach out if you have any questions or just want to say hello!

Copyright © 2021-2024 Ferdous Mahmud Akash. All rights reserved.
Made by Ferdous· Github
LinkTree