Home > Enterprise >  Error, self use in method call "getGpa" before all stored poperties are initialized
Error, self use in method call "getGpa" before all stored poperties are initialized

Time:06-16

class Classroom{
   var nameOfClass : String
   var students : [String]
   var grades : [Int]
   var gpa : Double
   var highestGrade : Int
 
 
   init(nameOfClass : String, students : [String], grades : [Int]){
       self.nameOfClass = nameOfClass
       self.students = students
       self.grades = grades
       self.gpa = self.getGpa()
       self.highestGrade = self.getHighestGrade()
   }
 
   func getGpa() -> Double{
       var sum : Int = 0
 
       for grade in grades{
           sum  = grade
       }
 
       var length : Double = Double(grades.count)
       var avg : Double = Double(sum) / length
       return avg
   }
 
   func getHighestGrade() -> Int{
       var max : Int = grades[0]
 
       for grade in grades{
           if grade > max{
               max = grade
           }
       }
 
       return max
   }
 
}

How would I be able to successfully declare gpa to getGpa() and highestGrade to getHighestGrade()? I keep running into the self used in method call error. Thank you so much for the help!

CodePudding user response:

Declare gpa and highestGrade like this

var gpa: Double!
var highestGrade: Int!

CodePudding user response:

A possible solution is to calculate the values in the init method with one-liners

class Classroom {
   var nameOfClass : String
   var students : [String]
   var grades : [Int]
   var gpa : Double
   var highestGrade : Int
 
   init(nameOfClass : String, students : [String], grades : [Int]){
       self.nameOfClass = nameOfClass
       self.students = students
       self.grades = grades
       self.gpa = Double(grades.reduce(0,  )) / Double(grades.count)
       self.highestGrade = grades.max() ?? 0
   }
}

Do you really need a class? And are all var really supposed to be mutated?

  • Related