iOS
swift4

Delegate in Swift

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 teachLesson() 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