传递数据时,如何使变量可识别为多个类?

时间:2018-11-24 21:39:26

标签: ios swift

我有一个传递字符串的函数,该函数确定我导航后的目的地vc将是哪个类。我还将数据传递给vc,无论最终将哪个类vc强制转换为。但是,出现了预期的错误

  

“ UIViewController”类型的值?没有成员....

因为vc还没有被强制转换为任何子类。

func passAndNavigateResultsFor(surveyName: String){

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    var vc = storyboard.instantiateInitialViewController()

    //Determining which class vc will be cast as

    if surveyName == "EFDizzinessSurveyTask" {
        let vc = storyboard.instantiateViewController(withIdentifier :surveyName) as! EFDizzinessSurveyResults
    } else if surveyName == "EFHipArthritisSurveyTask" {
        let vc = storyboard.instantiateViewController(withIdentifier :surveyName) as! EFHipArthritisSurveyResults
    } else if surveyName == "EFKoosKneeSurveyTask" {
        let vc = storyboard.instantiateViewController(withIdentifier :surveyName) as! EFKoosKneeSurveyResults
    } else if surveyName == "EFLEFSSurveyTask" {
        let vc = storyboard.instantiateViewController(withIdentifier :surveyName) as! EFLEFSSurveyResults
    } else if surveyName == "EFQuickDASHSurveyTask" {
        let vc = storyboard.instantiateViewController(withIdentifier :surveyName) as! EFQuickDASHSurveyResults
    } else if surveyName == "EFNeckDisabilitySurveyTask" {
        let vc = storyboard.instantiateViewController(withIdentifier :surveyName) as! EFNeckDisabilitySurveyResults
    }

    //Data that I want to pass through regardless of which class vc is cast as

    if (firstNameResult != nil) && (lastNameResult != nil) {
        self.fullName = self.firstNameResult! + " " + self.lastNameResult!
        vc.nameText = self.fullName!
    }
    if painLevelResult != nil {
        vc.painLevelText = String(describing: painLevelResult!)
    }
    if careSatisfactionResult != nil {
        vc.careSatisfactionText = String(describing: careSatisfactionResult!)
    }
    if rateProgressResult != nil {
        vc.rateProgressText = String(describing: rateProgressResult!)
    }
    if therapyGoalsResult != nil {
        vc.therapyGoalsText = String(describing: therapyGoalsResult!)
    }
    if step1Result != nil {
        vc.step1Text = String(describing: step1Result!)
    }
    if step2Result != nil {
        vc.step2Text = String(describing: step2Result!)
    }
    if step3Result != nil {
        vc.step3Text = String(describing: step3Result!)
    }
    if step4Result != nil {
        vc.step4Text = String(describing: step4Result!)
    }
}

是否有解决此问题的方法,还是应该使用prepareForSegue之类的解决方案?

1 个答案:

答案 0 :(得分:0)

被抛出的确切错误是什么?它不确切拥有什么成员?

我个人同意您的看法,并会像这样使用“准备赛格”:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let yourVC = segue.destination as? YourViewController {
        yourVC.painLevelText = painLevelText
    }
}

您可以在其中找到,投射和准备正确的VC。

如果找不到属性时遇到问题,则应考虑为VC创建超类来存储painLevelText之类的属性