不能调用类方法,不可用

时间:2019-03-20 19:13:42

标签: swift

几天前,我刚刚开始学习如何编码, 所以基本上我创建了一个Class Car,里面有属性和函数, 我要做的是从文本字段中获取数据并应用类函数

// Class
}

class Car{
    var carModelCountries: Dictionary <String, String>
    var carYear: Int
    var carEngine: Double
    var Carmodel: String

    init(carModel: String, carYear: Int, carEngine: Double) {
        self.carYear = carYear
        self.carModelCountries = [ "Kia": "Korean",
                          "Mercedes": "Germany",
                          "Chevy": "USA",
                          "Audi": "Germany",
                          "Bentley": "Great Britain"]
        self.carEngine = carEngine
        self.Carmodel = carModel


        func getCarCountry(carModel: String) ->String{
            for (value, key) in self.carModelCountries {
                if key == self.Carmodel{
                    return value
                }
            }

            return "Origin Unknown"

        }

        func getCarAge(carYear: Int) -> String{
            if self.carYear <= 2016{
                return "Car is old"
            }
            return "Car is Brand New"
        }

        func getCarFuelConsumption(forEngine: Double) -> String {
            if self.carEngine >= 3.0 {
                return "Consumes a lot"

            }
            return "Almost Nothing"
        }


    }
    }

// labels  @IBOutlet weak var resultsLabel: UILabel!
    @IBOutlet weak var carModelLabel: UITextField!

    @IBOutlet weak var carYearLabel: UITextField!
    @IBOutlet weak var carEngineLabel: UITextField!

// here I'm trying to initialize the class inside button function and then assign results to result Label
 //button pressed
    @IBAction func getInfoButton(_ sender: Any) {

         var car = Car.init(carModel: carModelLabel.text!, carYear: Int(carYearLabel.text!)!, carEngine: Double(carEngineLabel.text!)!)

        resultsLabel.text = car.getCarAge

    }

我收到此错误“类型'Car'的值没有成员'getCarAge'”

2 个答案:

答案 0 :(得分:0)

您已将getCarAge放在init方法内。

答案 1 :(得分:0)

使getCarAge和所有其他方法实例化方法(将它们移出init(...) {...})。否则,它们仅在init范围内可见。您还可以删除方法的参数,因为您使用的是类的属性

class Car {

    ...

    init(...) {...}

    func getCarAge() -> String {
        if self.carYear <= 2016 {
            return "Car is old"
        }
        return "Car is Brand New"
    }

    ...

}

接下来,当您需要调用此方法时,需要使用()

resultsLabel.text = car.getCarAge()

或者,您可以将getCarAge计为财产

init(...) {...}

var carAge: String {
    if carYear <= 2016 {
        return "Car is old"
    }
    return "Car is Brand New"
}

resultsLabel.text = car.carAge