Associated values in swift enumeration and how to use them

Associated values in swift enumeration :

In this tutorial, we will learn what is associated values in swift and how to use them. To learn more about associated values, suppose we are writing an iOS application in swift that will greet the user differently for the first time use and second time use.
For example,suppose user ‘Albert’ is using the app for the first time. It will show one message Hello Albert ! Welcome to our app.. Similarly, after 10 time when he will open,it will print Hey Albert ! Thank you for using our app for more than 10 times. Please give us a rating on Appstore.. How we are going to use it ? Yes,we have different ways to solve this problem but we will learn how to solve it using enum in swift :

Solving this problem using Associated values :

To solve this, we will use two different case in the enumeration. One will handle first time greet and the other one will handle 10 th time greet. So, let’s write some code :

enum Greet{
    case firstTime(name : String)
    case askToReview(name : String, count : Int)
}

The name of this enum is Greet and it has two case. First case firstTime has an Associated value of type String and the second case askToReview has Associated values of type (String,Int).

Now, we can create one variable of type Greet and pass it to a switch block to handle :

enum Greet{
    case firstTime(name : String)
    case askToReview(name : String, count : Int)
}


let greet : Greet = Greet.firstTime(name: "Albert")

switch greet{
case .firstTime(let name):
    print("Hello \(name) ! Welcome to our Application .")
case .askToReview(let name, let count):
    print("Hey \(name) ! Thank you for using our app for more than \(count) times. Please give us a rating on Appstore.")
}

It will print :

Hello Albert ! Welcome to our Application .

We can also write the switch case as below :

enum Greet{
    case firstTime(name : String)
    case askToReview(name : String, count : Int)
}

let greet : Greet = Greet.askToReview(name: "Albeert", count: 10)

switch greet{
case let .firstTime(name):
    print("Hello \(name) ! Welcome to our Application .")
case let .askToReview(name,count):
    print("Hey \(name) ! Thank you for using our app for more than \(count) times. Please give us a rating on Appstore.")
}

It will print :

Hey Albeert ! Thank you for using our app for more than 10 times. Please give us a rating on Appstore.

Leave a Reply