2016-11-16 11 views
3

私はスウィフト2.xの中で働いていたテストUIAlertControllerを助けるためにa trickを持っていた:__NSMallocBlock__をSwift 3の基になる型にキャストするにはどうすればよいですか?

extension UIAlertController { 

    typealias AlertHandler = @convention(block) (UIAlertAction) -> Void 

    func tapButtonAtIndex(index: Int) { 
     let block = actions[index].valueForKey("handler") 
     let handler = unsafeBitCast(block, AlertHandler.self) 

     handler(actions[index]) 
    } 

} 

これは、鋳造作業を作るための方法があるかもしれないと信じて私を誘惑fatal error: can't unsafeBitCast between types of different sizesスイフト3.xの、下に失敗します。誰もそれを把握できますか?

答えて

7

はスウィフト3.0.1に

extension UIAlertController { 

    typealias AlertHandler = @convention(block) (UIAlertAction) -> Void 

    func tapButton(atIndex index: Int) { 
     if let block = actions[index].value(forKey: "handler") { 
      let blockPtr = UnsafeRawPointer(Unmanaged<AnyObject>.passUnretained(block as AnyObject).toOpaque()) 
      let handler = unsafeBitCast(blockPtr, to: AlertHandler.self) 
      handler(actions[index]) 
     } 
    } 

} 

の作品解決策を見つけた(もともと、block値が実際のブロック、ブロック - あなたは明らかにポインタにキャストすることはできませんへのポインタではなくなりましたAlertHandler

+0

非常に助かりました、ありがとう! – xytor

0

あなたのUIAlertControllerがアクションシートの場合、ハンドラを実行する前にRobertの答えを変更してUIAlertControllerを終了することができます。

は、(アニメーション:真、完了:{()ハンドラ(self.actions [インデックス]で)})却下

を私はテストのために、この拡張機能を使用し、この修正なしで提示ビュー・コントローラのための私のアサーションが失敗しました。

関連する問題