Jake Jake - 6 months ago 22
Swift Question

Unable to access class variables

I have the following swift class

import Foundation

class Tips
{
//Variables
var totalBill: Float
var tipPercent: Int
var splitBy: Int

init(billAmount: Float, tipPercentage: Int, splitByPeople: Int)
{
totalBill = billAmount
tipPercent = tipPercentage
splitBy = splitByPeople
}

class func calculateTip() -> Float
{
var grandTotal = totalBill + ((totalBill * tipPercent)/100)
return grandTotal/splitBy
}

}


In the
calculateTip()
function, I am seeing an error called
Instance member "totalBill" cannot be used on type "Tips"


How do I fix this?

Answer

you should remove class keyword before func calculateTip() :

class func calculateTip() -> Float

become

func calculateTip() -> Float

Using class keyword make your function static, and so you cannot access to class member because, the class is not instanciated

I recommend to use Float everywhere:

class Tips
{
    //Variables
    var totalBill: Float
    var tipPercent: Float
    var splitBy: Float

    init(billAmount: Float, tipPercentage: Int, splitByPeople: Int)
    {
        totalBill = billAmount
        tipPercent = Float(tipPercentage) // <--convert
        splitBy = Float(splitByPeople) // <--convert
    }

    class func calculateTip() -> Float
    {
        var grandTotal = totalBill + ((totalBill * tipPercent)/100)
        return grandTotal/splitBy
    }

}