2016-01-10 71 views
0

我在Swift中編寫了一個NSURL擴展。這個AnyObject怎麼樣?有boolValue屬性

extension NSURL { 
    var isDir : Bool { 
    do { 
     var isDir : AnyObject? 
     try self.getResourceValue(&isDir, forKey: NSURLIsDirectoryKey) 
     if let result = isDir?.boolValue { 
     return result 
     } else { 
     return false 
     } 
    } catch { 
     return false 
    } 
    } 
} 

這有效。但是我發現有些人先把指針(isDIR)「投」到NSNumber。例子有:

我發現沒有文件說AnyObject符合BooleanType協議。那麼我在Swift中的代碼如何工作?

回答

1

命令 - 點選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?. 

自動完成功能會告訴你的,你可以調用方法的完整列表。它是巨大的

+0

那麼這些演員是多餘的,對嗎? – LShi

+0

你可以跳過劇組。只要確保使用可選綁定,因爲如果該方法對於基礎對象類型不存在,則會返回'nil'。 – vacawama

+0

謝謝。但在這種情況下,如果'isDir'不是'nil',它必須是'NSNumber',對吧?還有'(isDir as?NSNumber)?。boolValue'有一個cast和一個unwrapping,可能效率較低? – LShi

1

getResourceValue(_ *value*:forKey:)爲文檔表示_ *value*:AutoreleasingUnsafeMutablePointer<AnyObject?>類型,這意味着它基本上是一個空指針可以被轉換爲任何類型,只要它是一個適當的類型。因此,isDirBool直接鑄造會工作,因爲這基本上是它是什麼,一個布爾類型:

let boolResult: Bool = isDir as! Bool 

只是可以作爲一個直接鑄造的,因爲它是一個void類型開始。

相關問題