作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
使用结构属性时,我不断收到“无法分配给值:‘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)
}
}
这是我在第一个页面 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)
}
}
错误发生在第 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 - 使用结构体时不断收到 "Cannot assign to value: 'calculateBMI' is a method",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62119337/
我是一名优秀的程序员,十分优秀!