LoginSignup
3
0

More than 5 years have passed since last update.

Delegate in Swift

Last updated at Posted at 2018-05-16

Delegate System in Swift

Delegate in Swift is a way of passing the data between class and class.

Let's say the teacher want to teach lesson to the student. So first of all we have to create a teacher. In this case teacher is a person who already understand the lesson. So we will create a protocol Learn for teacher here:


protocol Learn {
    func learnLesson()
}

Now let's create a teacher who conform to the Learn protocol:

struct Teacher: Learn {
    func learnLesson() {
        print("This is lesson 1")
    }
}

Now Teacher has the ability to print out lesson 1:

var teacher = Teacher()
teacher.learnLesson() // this line of code will print out "This is lesson 1"

A student want to learn lesson 1 from him, now he can delegate function learnLesson() to his student. Let's create a student who want to learn lesson 1:

struct Student {
    var delegate: Learn?
}

Now, we have a student that want to learn lesson. Let's delegate learnLesson to him:

var student = Student()
student.delegate = teacher

Now the student learned lesson 1 from the teacher:

student.delegate?.learnLesson() // This is lesson 1
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0