2016-08-23 10 views
2

Swiftで#functionを使用してメソッドが呼び出されたかどうかを検出しようとしましたが、#selectorの説明とは異なる結果が返されます。ここで作業コードです:上記サンプルからSwiftの#functionと#selectorの結果が異なります

class SampleClass { 

    var latestMethodCall: Selector? 

    @objc func firstMethod() { 
     latestMethodCall = #function 
    } 

    @objc func secondMethod(someParameters: Int, anotherParameter: Int) { 
     latestMethodCall = #function 
    } 

    func isEqualToLatestMethod(anotherMethod anotherMethod: Selector) -> Bool { 
     return latestMethodCall?.description == anotherMethod.description 
    } 
} 


let sampleObject = SampleClass() 

sampleObject.firstMethod() 

let expectedFirstMethod = #selector(SampleClass.firstMethod) 

if sampleObject.isEqualToLatestMethod(anotherMethod: expectedFirstMethod) { 

    print("Working correctly!") 

} else { 

    print("Broken selector...") 

    if let latestMethodCall = sampleObject.latestMethodCall { 
     print("Object's latest method call: \(latestMethodCall.description)") // prints firstMethod() 
     print("Expected method call: \(expectedFirstMethod.description)") // prints firstMethod 
    } 
} 

sampleObject.secondMethod(5, anotherParameter: 7) 

let expectedSecondMethod = #selector(SampleClass.secondMethod(_:anotherParameter:)) 

if sampleObject.isEqualToLatestMethod(anotherMethod: expectedSecondMethod) { 

    print("Working correctly!") 

} else { 

    print("Broken selector...") 

    if let latestMethodCall = sampleObject.latestMethodCall { 
     print("Object's latest method call: \(latestMethodCall.description)") // prints secondMethod(_:anotherParameter:) 
     print("Expected method call: \(expectedSecondMethod.description)") // prints secondMethod:anotherParameter: 
    } 
} 

、私は発見した#function戻りスウィフト-Y説明、#selector戻るにObjC-Y説明します。これは期待されていますか?あるいは私は何か間違ったことをしましたか?

ありがとうございました! :)

答えて

1

スウィフト< 3.0 SelectorタイプはStringで初期化できます。これを行うのは安全ではないので(このアプローチは動的Objective-Cに由来します)、#selectorがSwift 2.2に導入されました。 #selectorは存在しないメソッドに対してSelectorを定義することを許可しません。

Selectorを文字列で初期化してみましょう。セレクタの文字列は厳密に特殊なシグネチャを持つ必要があります:引数なしのメソッドの場合func firstMethod()それは、中括弧なしのメソッド名です:"firstMethod"です。一方、#functionキーワードはSelector年代を定義するために絶対にないように、それは中括弧で機能ラベルを返します。

@objc func firstMethod() { 
    print(#function) 
} 
//firstMethod() 

あなたは引数を持つメソッドを定義する場合は、あなたが#functionが今と同じ返されることがわかりますが、中括弧なしでます

@objc func firstMethod(param: Int) { 
    print(#function) 
} 
//firstMethod 

Selector以来、再び、それを他の署名を期待する:"firstMethod:"

結論:定義のためにSelector使用#selector; Swift> = 3.0では、とにかく選択肢はありません。

+1

ああ、私は見る...私はSwift 2.2を使っていることを付け加えて忘れてしまった。あなたの結論によると、 'firstMethod'では' #selector(SampleClass.firstMethod) 'と' secondMethod'では '#selector(SampleClass.secondMethod(_:anotherParameter :))'を 'latestMethodCall'に割り当てるべきでしょうか? – edopelawi

+1

'#function'を'#selector'に変更しようとしましたが、それは完璧に機能しました!どうもありがとうございました! – edopelawi

関連する問題