1.

What will be output for below code snippet? Also, analyze the memory performance for this code.

Answer»

OUTPUT:

Albert Einstein GOT 80.0 marks in this EXAM 80.0 for Albert Einstein in this exam. Here we have defines two classes, Student and ScoreCard. Each student owns one scoreCard also Each scoreCard belongs to the specific student.

Finally, we have created a student with the name  "Albert Einstein" and ScoreCard with 80 marks. We assigned scorecard to student and student to scorecard. Now both objects are strongly REFERENCING to each other. So they will never be removed from memory. This code will cause a memory leak.

To fix this, we have to use weak reference for scoreCard property of student class.

class Student {    let name: String    init(name: String) {        self.name = name    }    weak var scoreCard: ScoreCard?{        didSet{            print("\(name) got \(scoreCard!.marks) marks in this exam")        }    } }


Discussion

No Comment Found

Related InterviewSolutions