我試圖檢測一個方法是否在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.secondMethod(_:anotherParameter :))'''secondMethod'分配帶有'#selector(SampleClass.firstMethod)'的'latestMethodCall',對吧? – edopelawi
只是試着改變'#功能'到'#選擇器',它完美的工作!非常感謝你! – edopelawi