无法访问类变量

时间:2016-05-11 01:32:08

标签: swift

我有以下快速课程

availabilityID

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 } } 函数中,我看到一个名为calculateTip()

的错误

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

你应该在func calculateTip()之前删除 class 关键字:

class func calculateTip() -> Float

成为

func calculateTip() -> Float

使用关键字使您的函数保持静态,因此您无法访问类成员,因为该类未实现

我建议在任何地方使用Float:

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
    }

}