Swift条件绑定

时间:2015-12-13 17:49:16

标签: ios swift enums switch-statement uikit

我正在使用Swift构建iOS应用程序。当我想用segue呈现它们时,我有三个UIViewControllers和一个枚举。

class a: UIViewController {}
class b: UIViewController {}
class c: UIViewController {}

我正在编写一个迭代它们的函数,如果c是当前的那个,那么我需要设置一个属性。然后使用我的a,b,c实例。

// Segues 
func segue(sender: Button) {
    let title = sender.destination!
    switch title {
    case .NewWorkout:
        let VC: NewWorkout = NewWorkout()
    case .Home:
        let VC: Home = Home()
    case .Preview:
        let VC: WorkoutPreview = WorkoutPreview()
        VC.type = .allWorkouts
    } // 1

    self.presentViewController(VC, animated: true, completion: nil) // 2
}

我得到的错误是Expected expression in assignment在第2行的1和Use of unresolved identifier "VC"的行上。我明白我的问题是VC是在switch语句中创建的并且不是在它的独家新闻之外。感谢。

3 个答案:

答案 0 :(得分:2)

只需在 switch语句之前定义VC变量

let VC : UIViewController

switch title {
    case .NewWorkout:
        VC = NewWorkout()
    case .Home:
        VC = Home()
    case .Preview:
        let workoutPreview = WorkoutPreview()
        workoutPreview.type = .allWorkouts
        VC = workoutPreview
}

self.presentViewController(VC, animated: true, completion: nil)

请注意,您可以使用VClet声明为(非可选)常量 如果在交换机中处理所有可能的枚举值。如有必要,您可以添加

    default:
       fatalError("Unexpected title")

答案 1 :(得分:1)

我想你可能会想要这样的东西:

//: Playground - noun: a place where people can play

import UIKit

enum ControllerType {
    case allWorkouts
}

class NewWorkoutController: UIViewController { }
class HomeController: UIViewController { }
class WorkoutPreviewController: UIViewController {
    var type: ControllerType?
}

enum Destination {
    case NewWorkout
    case Home
    case Preview

    var controller: UIViewController {
        switch self {
        case NewWorkout:
            return NewWorkoutController()
        case Home:
            return HomeController()
        case Preview:
            let vc = WorkoutPreviewController()
            vc.type = .allWorkouts
            return vc
        }
    }
}

class Button: UIButton {
    var destination: Destination?
}

class ViewController: UIViewController {
    func segue(sender: Button) {
        if let vc = sender.destination?.controller {
            self.presentViewController(vc, animated: true, completion: nil)
        }
    }
}

答案 2 :(得分:0)

您的问题是,您在交换机内声明VC,因此当您使用VC进行预测时,它不知道VC是什么。 VC超出presentViewController的范围。这是你可以做的一种方式:

func segue(sender: Button) {
    let title = sender.destination!
    var VC:UIViewController
    switch title {
        case .NewWorkout:
            VC = NewWorkout()
        case .Home:
            VC = Home()
        case .Preview:
            VC = WorkoutPreview()
            VC.type = .allWorkouts
    } // 1

    self.presentViewController(VC, animated: true, completion: nil) // 2
}

所以现在VC与调用presentViewController的范围相同。