gpt4 book ai didi

swift - 这个AnyObject怎么可能?具有 boolValue 属性

转载 作者:行者123 更新时间:2023-11-28 12:57:20 25 4
gpt4 key购买 nike

我用 Swift 写了一个 NSURL 扩展。

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 协议(protocol)。那么我的 Swift 代码如何工作?

最佳答案

Command-点击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?

在 Playground 中,然后:

a?.

自动完成将显示您可以调用的方法的完整列表。而且它巨大

关于swift - 这个AnyObject怎么可能?具有 boolValue 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34702026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com