typealias AnyObject
Discussion 解説
You can use the Any
protocol as the concrete type for an instance of any class. When you do, all known @objc
class methods and properties are available as implicitly unwrapped optional methods and properties, respectively. For example:
あなたはAny
プロトコルをあらゆるクラスのインスタンスに対して具象型として使うことができます。あなたがそうする場合、全ての既知の@objc
クラスのメソッドおよびプロパティは、暗黙的にアンラップされるオプショナルのメソッドおよびプロパティとしてそれぞれが利用可能です。例えば:
class IntegerRef {
@objc class func getDefaultValue() -> Int {
return 42
}
}
func getDefaultValue(_ c: AnyClass) -> Int? {
return c.getDefaultValue?()
}
The get
function uses optional chaining to safely call the implicitly unwrapped class method on c
. Calling the function with different class types shows how the get
class method is only conditionally available.
get
関数は、オプショナル連鎖を使って、暗黙的にアンラップされるクラスメソッドをc
上で安全に呼び出します。この関数を異なるクラス型で呼び出すことは、どのようにget
クラスメソッドが条件付きでのみ利用可能であるのかを示します。
print(getDefaultValue(IntegerRef.self))
// Prints "Optional(42)"
print(getDefaultValue(NSString.self))
// Prints "nil"