使用struct属性时,我不断收到“无法分配给值:'calculateBMI'是一种方法”的错误消息。任何解决方法。这是我的结构代码:

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)
}
}

这是我在“第一页视图”控制器上收到错误消息的位置:
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)


}
}

该错误发生在第43行(calculations.calculateBMI)

最佳答案

由于错误明确指出,您正在尝试设置calculateBMI,它是一个函数而不是一个变量。要解决此问题,请像这样修改您的calculatePressed方法:

@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)
}

关于ios - 使用结构时,不断出现“无法分配值:'calculateBMI'是一种方法”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62119337/

10-09 18:32