2017-01-03 10 views
0

私はJava \ C#の背景からスウィフトに入っていますが、1つのことを理解することはできません。 C#のイベント(Action<T>)と同様のSwiftオブジェクトに通知イベントを作成する方法はありますか?SwiftにはC#のイベントと同様のイベントの概念がありますか?

または、私はこの目的でクロージャを使用しますか?

+0

protocol SampleProtocol: class { func didLoad() func didAppear() } class ViewController: UIViewController, SampleProtocol { override func viewDidLoad() { super.viewDidLoad() let secondViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SecondVC") as! SecondViewController secondViewController.configure(delegate: self) addChildViewController(secondViewController) view.addSubview(secondViewController.view) } func didLoad() { print ("didLoad") } func didAppear() { print ("didAppear") } } class SecondViewController: UIViewController { weak var delegate: SampleProtocol? override func viewDidLoad() { super.viewDidLoad() delegate?.didLoad() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) delegate?.didAppear() } func configure(delegate: SampleProtocol) { self.delegate = delegate } } 
[プロパティオブザーバー(https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html#//apple_ref/doc/uid/TP40014097-CH14-ID262 )、 私は推測する。 – Moritz

答えて

0

私が理解しているように、C#のAction<T>デリゲートは、単純にVoid - デリゲートを介して実行可能なメソッドをカプセル化する戻り関数デリゲートです。

struct Action<T> { 
    private let f: (T) ->() 

    init(_ f: @escaping (T) ->()) { 
     self.f = f 
    } 

    func run(_ val: T) { 
     f(val) 
    } 
} 

私たちは、これを使用することができます

スウィフトサポート高次機能するので、あなたはtypeholderタイプTの単一引数にVoid -returning方法をカプセル化する単一の目的で独自のAction<T>タイプを定義することができます例えば

func addOneAndPrint(val: Int) { 
    print(val+1) 
} 

let increaseAndPrintAction = Action(addOneAndPrint) // inferred to Action<Int> 
increaseAndPrintAction.run(1) //2 

または(C#でAction<T>にラムダの供給と同様に)供給される閉鎖:機能カプセル化するために今

let increaseAndPrintAction = Action { print($0 + 1) } 
increaseAndPrintAction.run(1) // 2 
[1, 3, 5].forEach(increaseAndPrintAction.run) // 2 4 6 

を、IはC#でAction<T>の一般的な使用例を知りませんいくつかのタスクの完了時に何らかのイベントを実行するために使用する場合は、実行するタスクにクロージャーとして提供された完了ハンドラーを単に使用することができます:

func increaseTask(_ val: inout Int, completion: (Int) ->()) { 
    val += 1 
    // ... 
    completion(val) 
} 

var val = 1 
increaseTask(&val) { print("Successfully increased to value \($0)") } 
    // Successfully increased to value 2 
print(val) // 2 
0

デリゲートとプロトコルを使用してこれを行うことができます。ここでは、ViewControllerとSecondViewControllerという2つのViewControllerを持つストーリーボード(ストーリーボードIDが "Main"の場合)を想定した簡単な例を示します。

関連する問題