【问题标题】:My global var is losing its value from one function to another我的全局变量正在从一个函数到另一个函数失去它的价值
【发布时间】:2019-04-19 14:18:56
【问题描述】:

我有一个应用程序,当按下按钮时应该设置一个自定义 var,然后用于配置准备 segue 功能。基本上在准备函数中,我设置了一个 switch 语句来执行适当的代码。

但是,如果我在 IBAction 函数中为按钮设置开关将使用的 var,则 var 在执行开关命令之前会丢失其值,而我得到的只是“失败”的默认值。

我一直在寻找,我知道我在做一些非常愚蠢的事情,但我是一个菜鸟,如果有任何帮助,我需要一些帮助!

import UIKit

var mainAppointment = Appt()

class SubMenuOneViewController: UIViewController {
    // func whatsTheService() -> ServiceType {
    //     let serviceSelected = ServiceType.appointment
    //      return serviceSelected
    //  }

    @IBAction func selectAppointmentSetting(_ sender: myFirstButton) {
        //let whatsSelected = serviceTypeSelected.airport

        mainAppointment.serviceType = .petvisit
        mainAppointment.petName = "Beans"
        performSegue(withIdentifier: "appointmentSettingSegue", sender: self)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let nav = segue.destination as! UINavigationController
        let apptOrderVC = nav.topViewController as! AppointmentScreenTableViewController

        //switch (serviceTypeSelected).self {
        switch mainAppointment.petName {
        case "Beans":
            apptOrderVC.appointmentTypeString = "Beans"
        default:
            apptOrderVC.appointmentTypeString = "fail"
        }
    }

【问题讨论】:

  • “var 失去了它的价值”是什么意思?你得到的价值是什么?另外,你能发布Appt class/struct 是什么吗?
  • “失去价值”是什么意思? mainAppointment 的初始化方式是非可选的,所以它不能是 nil
  • 我会设置一些断点来验证预期的流程。一个是确保petName 设置在selectAppointmentSetting 中(顺便说一句,签名是错误的——它应该类似于sender: <type_of_sender>),另一个是检查prepare(for:) 中的值是否正确。最后,您真的需要一个全局变量吗?...
  • 当我说失去价值时,它是“”。使用调试器时,值会在按钮单击时正确设置,但当 segue 启动时 Petname 的值会返回到“”。 As far as a global var being needed, probably not but I'm experimenting with different workflows at the moment and this is the one I'm trying for now.. Basically I want a few buttons that when selected will collect some data and then从按钮单击动作发送到 Prepare for Segue。不知何故,从按钮单击到 segue 执行的转换正在消失。
  • 我应该提到,当我运行应用程序时,值“fail”是向前发送的值,因此正在使用开关,但认为 Petname 为空白。感谢您的及时反馈,你们太棒了!

标签: swift var


【解决方案1】:

好吧,我尝试了一种不同的方法,在准备转场函数中使用转场标识符,并且效果很好。可能是更好的方法!感谢所有反馈!

   if segue.identifier == "appointmentSettingSegue" {
            apptOrderVC.appointmentTypeString = "Beans"
        } else {
            apptOrderVC.appointmentTypeString = "fail"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-21
    • 1970-01-01
    • 2019-07-03
    • 1970-01-01
    • 2015-09-30
    • 2015-04-12
    相关资源
    最近更新 更多