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説明します。これは期待されていますか?あるいは私は何か間違ったことをしましたか?
ありがとうございました! :)
ああ、私は見る...私はSwift 2.2を使っていることを付け加えて忘れてしまった。あなたの結論によると、 'firstMethod'では' #selector(SampleClass.firstMethod) 'と' secondMethod'では '#selector(SampleClass.secondMethod(_:anotherParameter :))'を 'latestMethodCall'に割り当てるべきでしょうか? – edopelawi
'#function'を'#selector'に変更しようとしましたが、それは完璧に機能しました!どうもありがとうございました! – edopelawi