初始声明后struct不更新的值

问题描述 投票:0回答:2

我正在尝试制作一个专门的计算应用程序,但在几天前开始这个项目之前,他几乎没有使用swift或iOS开发经验以及一些Java经验。

我试图将结构变量从一个视图控制器传递到另一个视图控制器,然后通过实例化获取这些变量。

这是包含结构的代码:

            struct SSDCalcs {
            var patientInput: String
            var siteInput: String
            var scriptInput: Double
            var depthInput: Double
            var fieldInput: Double
            var length: Double
            var width: Double
            var squareInput: Double
        }

        //Change values of struct when enter key pressed
        @IBAction func enterPressed(_ sender: Any) {
                calcResults = SSDCalcs(patientInput: patientID.text!, siteInput: "fdfadsf", scriptInput: 5.0, depthInput: 6.0, fieldInput: 7.0, length: 8.0, width: 9.0, squareInput: 15.0)
       }


    //Initial delcaration of struct values (So the results page class doesn't complain about "calcResults" not yet existing"
    var calcResults = SSDCalcs(patientInput: "Error: Wrong struct values", siteInput: "Error", scriptInput: 0.0, depthInput: 0.0, fieldInput: 0.0, length: 0.0, width: 0.0, squareInput: 0.0)

}

这是我从其他类的结果页面代码:

func setValues() {
    var SSDCalcs = SSDCalculation().calcResults
    self.SSDPatientRef.text = "Patient ID: " + SSDCalcs.patientInput
    self.SSDSiteRef.text = "Treatment Site: " + SSDCalcs.siteInput
    self.SSDScriptRef.text = "Script (cGy): " + String(SSDCalcs.scriptInput)
    self.SSDDepthRef.text = "Depth: " + String(SSDCalcs.depthInput)
    self.SSDFieldRef.text = "Field Size: " + String(SSDCalcs.fieldInput)
    self.SSDLengthRef.text = "Length: " + String(SSDCalcs.length)
    self.SSDWidthRef.text = "Width: " + String(SSDCalcs.width)
    self.SSDSqrRef.text = "Equivalent Square: " + String(SSDCalcs.squareInput)
}

编译或运行代码时没有错误...只要在输入字段的页面上按下“enter”键,它就不会自动更新。根据xcode调试器(Breakpoints are life),当按下输入UIButton时,该方法会激活,值会更改,但是当在结果页面上显示时,假设的更改消失了,而是显示它们的初始声明值。

我认为加载新视图时可能会擦除数据......但我不知道如何绕过它。

任何帮助将不胜感激!

ios swift
2个回答
0
投票

这一行:

var SSDCalcs = SSDCalculation().calcResults

始终创建一个具有初始结果的SSDCalculation结构的新实例。它不会引用您可能已创建的任何其他实例。


1
投票

Swift结构是值类型:

值类型是一种类型,在将值分配给变量或常量时,或者将值传递给函数时,将复制该值。

这就是您在传递的struct实例上应用的更改不会影响该结构的原始实例的原因。

有关更多信息,请查看Swift的documentation结构。

结构和枚举是类型中的值,类是引用类型。

Swift整数,浮点数,布尔值,字符串,数组和字典中的所有基本类型都是值类型,并在幕后实现为结构。

© www.soinside.com 2019 - 2024. All rights reserved.