2017-05-11 8 views
-1

クロージャ/構造体/キャプチャのプロパティに問題があります。iOS Swift。構造体コンストラクタでクロージャ内のプロパティを取得する

私は本当にアーキテクチャを説明することはできませんが、私はこのような何か持っている必要があります。

class ControllerAAA { 
    struct Events { 
     var userDidSelect(_ controller: Controller) ->()? 
    } 
} 

class ControllerBBB { 
    var foo: Foo 

    var events: ControllerAAA.Events(userDidSelect: { 
     (controller: Controller) ->()? in 
     // Here i need foo. Self mean the Block not the Controller 
    }) 

    // Then i will passed events when i call ControllerAAA and ControllerAAA will use events.userDidSelect(...) when he is done. 
} 

は、クラスで定義された構造体のコンストラクタである閉鎖で「自己」に到達することが可能ですか?

+0

あなたは、コードのあなたの完全なセットを示すことがありますか?表示されていない 'ControllerAAA.Events'呼び出しで' init'を使っているようです。インスタンス化のラベルは、おそらく 'userDidCancel:'の代わりに 'userDidSelect:'を読み込むはずですか? –

+0

申し訳ありませんが、userDidCancelがエラーでした。 それは実際にはまったく実際のコードではありません。 – Nek

答えて

0

コールバックブロックを定義する時点では、クラスのレキシカルスコープにあり、クラスのインスタンスではありません。これを解決するには、インスタンスメソッドのコンテキストでコールバックを初期化する必要があります。

私のような何かを試してみてください:

enum ControllerAEvent { 
    case userDidSelect((_ controller: Controller) ->()) 
} 

class ControllerBBB { 
    var foo: String 

    var events: ControllerAEvent 

    init() { 
     events = .userDidSelect({ 
      (controller: Controller) ->() in 

      Print(self.foo) 
     }) 
    } 
    // Then i will passed events when i call ControllerAAA and ControllerAAA will use events.userDidSelect(...) when he is done. 
} 
+0

私は近くでそれをテストできるようにしています。しかし、実際に別の問題が発生しました。どうすればControllerAEvent.userDisSelect(...)を呼び出すことができますか? 列挙要素「userDidSelectインスタンス部材 – Nek

+0

'FUNC fireEvent(イベント:ControllerAEvent)として参照することはできません:{ スイッチイベント{ 場合.userDidSelect(eventCallback): eventCallback(自己) } }'ここ は、エラーであります –

+0

Not working:/何とかやろうとします。手伝ってくれてありがとう ! – Nek

関連する問題