Keep getting "Cannot assign to value: 'calculateBMI' is a method" when using a struct

Viewed 46

I keep getting "Cannot assign to value: 'calculateBMI' is a method" error message when using a struct property. any way around this. This is my code from the struct:

import UIKit

struct Calculations {

var bmi : Float = 0.0

func getBMIValue() -> String {
   let BMIRounded = String(format: "%.1f", bmi)
    return BMIRounded
}

mutating func calculateBMI (height: Float, weight: Float) {
    bmi = weight / (height * height)
}
}

and this is where I get the error message on my First Page View controller:

import UIKit

class HomeViewController: UIViewController {

var calculations = Calculations()

@IBOutlet weak var heightLabel: UILabel!
@IBOutlet weak var weightLabel: UILabel!
@IBOutlet weak var heightSlider: UISlider!
@IBOutlet weak var weightSlider: UISlider!


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}

@IBAction func HeightSliderChange(_ sender: UISlider) {
    var height = String (format: "%.2f", sender.value)
    heightLabel.text = "\(height)m"
    print(height)

}

@IBAction func WeightSliderChange(_ sender: UISlider) {
    var weight = String (format: "%.0f", sender.value)
    weightLabel.text = "\(weight)kg"

}

@IBAction func calculatePressed(_ sender: Any) {
    let height = heightSlider.value
    let weight = weightSlider.value

    calculations.calculateBMI = (height: height, weight: weight)
    self.performSegue(withIdentifier: "GettingResults", sender: self)


}
}

The error happens on line 43 (calculations.calculateBMI)

1 Answers

As the error states clearly you are trying to set calculateBMI which is a function and not a variable. To fix this issue modify your calculatePressed method like this:

@IBAction func calculatePressed(_ sender: Any) {
    let height = heightSlider.value
    let weight = weightSlider.value

    calculations.calculateBMI(height: height, weight: weight)
    self.performSegue(withIdentifier: "GettingResults", sender: self)
}
Related