2014-10-27 7 views
1

我有一个问题,转换目标c为swift。self.navigationController.topViewController as HomeViewController

对于我的火车,我转换MMPaper到迅速,但在属性:

目标c

- (void)interactionBeganAtPoint:(CGPoint)point 
{ 
    // Very basic communication between the transition controller and the top view controller 
    // It would be easy to add more control, support pop, push or no-op 
    HASmallCollectionViewController *presentingVC = (HASmallCollectionViewController *)[self.navigationController topViewController]; 

    HASmallCollectionViewController *presentedVC = (HASmallCollectionViewController *)[presentingVC nextViewControllerAtPoint:point]; 
    if (presentedVC!=nil) 
    { 
     [self.navigationController pushViewController:presentedVC animated:YES]; 
    } 
    else 
    { 
     [self.navigationController popViewControllerAnimated:YES]; 
    } 
} 

夫特

func interactionBeganAtPoint(point: CGPoint) { 
     var presentingVC: HomeViewController! = (self.navigationController.topViewController as HomeViewController) 
     var presentedVC: HomeViewController! = (presentingVC.nextViewControllerAtPoint(point) as HomeViewController) 

     if (presentedVC != nil) { 
      self.navigationController.pushViewController(presentedVC!, animated: true) 
     } else { 
      self.navigationController.popViewControllerAnimated(true) 
     } 
    } 

结果是(问题以粗体显示):

libswiftCore.dylib`swift_dynamicCastClassUnconditional: 
... 
0x10cf7da1e: leaq 0x36b3d(%rip), %rax  ; "Swift dynamic cast failed" 
0x10cf7da25: movq %rax, 0xb4a2c(%rip)  ; gCRAnnotations + 8 
0x10cf7da2c: int3 
**0x10cf7da2d: movq %rdi, %rax** 
..... 

你有想法吗?

回答

1

通过使用as运算符,您告诉Swift,您完全确定您向下倾斜到HomeViewController会成功。但是,明确presentingVC.nextViewControllerAtPoint(point)可以返回nil,并且不能成功下降nilHomeViewController

当向下转换可能失败时,请使用as?运算符返回您要转换为的类型的可选值。

下面应该工作:

func interactionBeganAtPoint(point: CGPoint) { 
    let presentingVC = self.navigationController.topViewController as? HomeViewController 

    if let presentedVC = presentingVC?.nextViewControllerAtPoint(point) as? HomeViewController { 
     self.navigationController.pushViewController(presentedVC, animated: true) 
    } else { 
     self.navigationController.popViewControllerAnimated(true) 
    } 
} 

(我也利用了类型推断使代码更简洁;当斯威夫特看到as? HomeViewController,它的数字指出的presentingVC类型必须是HomeViewController?。对不起,如果这是显而易见的。)

+0

我试过 var presentingVC:HomeViewController! presentationVC = self.navController.topViewController as HomeViewController println(“presentsVC = \(presentingVC)”) var presentedVC:HomeViewController!presentedVC =呈现VC?.nextViewControllerAtPoint(点)为? HomeViewController 的println( “presentedVC = \(presentedVC)”) 结果: presentingVC = presentedVC =零 我不understant,为什么presentedVC是零! – macben 2014-10-29 15:40:21