命令 - 點選AnyObject
,你會找到答案:
/// The protocol to which all classes implicitly conform.
///
/// When used as a concrete type, all known `@objc` methods and
/// properties are available, as implicitly-unwrapped-optional methods
/// and properties respectively, on each instance of `AnyObject`. For
/// example:
///
/// class C {
/// @objc func getCValue() -> Int { return 42 }
/// }
///
/// // If x has a method @objc getValue()->Int, call it and
/// // return the result. Otherwise, return nil.
/// func getCValue1(x: AnyObject) -> Int? {
/// if let f:()->Int = x.getCValue { // <===
/// return f()
/// }
/// return nil
/// }
///
/// // A more idiomatic implementation using "optional chaining"
/// func getCValue2(x: AnyObject) -> Int? {
/// return x.getCValue?() // <===
/// }
///
/// // An implementation that assumes the required method is present
/// func getCValue3(x: AnyObject) -> Int { // <===
/// return x.getCValue() // x.getCValue is implicitly unwrapped. // <===
/// }
///
/// - SeeAlso: `AnyClass`
@objc public protocol AnyObject {
}
所以,你可以調用一個AnyObject
實例的任何@objc方法。
如果鍵入
let a: AnyObject?
在操場,然後
:
a?.
自動完成功能會告訴你的,你可以調用方法的完整列表。它是巨大的。
那麼這些演員是多餘的,對嗎? – LShi
你可以跳過劇組。只要確保使用可選綁定,因爲如果該方法對於基礎對象類型不存在,則會返回'nil'。 – vacawama
謝謝。但在這種情況下,如果'isDir'不是'nil',它必須是'NSNumber',對吧?還有'(isDir as?NSNumber)?。boolValue'有一個cast和一個unwrapping,可能效率較低? – LShi