我试图在Swift中的视图之间传递一个int变量,但是我不确定如何访问其他View控制器的属性。

在 objective-c 中,我会这样做

UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
AnsViewController *ansViewController = [storyBoard instantiateViewControllerWithIdentifier:@"ansView"];
ansViewController.num = theNum;
[self presentViewController:ansViewController animated:YES completion:nil];

在另一个viewcontroller.h文件中,我将编写此代码以声明属性以获取数据
@property (nonatomic) int num;

现在对于Swift我有这个
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let ansViewController : UIViewController = storyBoard.instantiateViewControllerWithIdentifier("ansView") as UIViewController
ansViewController.num = theNum;
self.presentViewController(ansViewController, animated:true, completion:nil)

在另一个视图控制器的另一个.swift文件中,我通过执行
let num: int

我很确定这不是正确的方法,因为我在此行遇到错误
ansViewController.num = theNum;

并显示“UIViewController没有名为num的成员”,我该如何解决此错误,我做错了什么?

谢谢

最佳答案

问题

在 objective-c 中,您已将ansViewController明确定义为AnsViewController *,具有属性num。

在您的Swift代码中,您已经将ansViewController明确定义为UIViewController,而不是AnsViewController。因此,编译器不知道这实际上是AnsViewController还是其他UIViewController子类,还是仅仅是普通的UIViewController。

现在提供解决方案。

我们将尝试将返回的值作为AnsViewController进行向下转换,如果向下转换成功,则访问该属性(我假设它始终会成功,但是与您的其余代码和笔尖无关,我可以'不能确定)。

let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

// To be safe, let's attempt to downcast the returned value as an AnsViewController
if let ansViewController = storyBoard.instantiateViewControllerWithIdentifier("ansView") as? AnsViewController {
    // We get here if the "as?" succeeds with a non-nil value
    ansViewController.num = theNum;
    self.presentViewController(ansViewController, animated:true, completion:nil)
} else {
    // Out of context, I can't see why this case would (or could) ever happen
}

现在,如果您知道这将始终成功(从我的看到,-instantiateWith ...的返回值是确定性的),那么您可以更加简洁一些:
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

// Force the downcast as an AnsViewController (this could crash at runtime
// if the return value is nil or not an AnsViewController, so again,
// the previous example is safer
let ansViewController = storyBoard.instantiateViewControllerWithIdentifier("ansView") as AnsViewController
ansViewController.num = theNum;
self.presentViewController(ansViewController, animated:true, completion:nil)

10-08 07:28