typealias AnyClass
Discussion 解説
You use Any
when you need the flexibility of an untyped object or when you use bridged Objective-C methods and properties that return an untyped result. Any
can be used as the concrete type for an instance of any class, class type, or class-only protocol. For example:
あなたが型付けされないオブジェクトの柔軟性を必要とするとき、または型付けされない結果を返すブリッジされたObjective-Cメソッドやプロパティを使用するとき、あなたはAny
を使います。Any
は、あらゆるクラス、クラス型、またはクラス専用プロパティのインスタンスに対する具象型として使われることができます。例えば:
class FloatRef {
let value: Float
init(_ value: Float) {
self.value = value
}
}
let x = FloatRef(2.3)
let y: AnyObject = x
let z: AnyObject = FloatRef.self
Any
can also be used as the concrete type for an instance of a type that bridges to an Objective-C class. Many value types in Swift bridge to Objective-C counterparts, like String
and Int
.
Any
はまた、Objective-Cクラスへとブリッジするある型のインスタンスに対する具象型として使われることができます。Swiftでの多くの値型は、Objective-Cの相当物へとブリッジします、String
やInt
のように。
let s: AnyObject = "This is a bridged string." as NSString
print(s is NSString)
// Prints "true"
let v: AnyObject = 100 as NSNumber
print(type(of: v))
// Prints "__NSCFNumber"
The flexible behavior of the Any
protocol is similar to Objective-C’s id
type. For this reason, imported Objective-C types frequently use Any
as the type for properties, method parameters, and return values.
Any
プロトコルの柔軟な挙動は、Objective-Cのもつid
型に似ています。この理由から、インポートされたObjective-C型はしばしばAny
をプロパティ、メソッドパラメータ、そして戻り値の型として使います。
Casting AnyObject Instances to a Known Type AnyObjectインスタンスを既知の型へキャストする
Objects with a concrete type of Any
maintain a specific dynamic type and can be cast to that type using one of the type-cast operators (as
, as?
, or as!
).
具象型としてAny
を持つオブジェクトは、特定の動的型を保守して、その型へと型キャスト演算子(as
、as?
。またはas!
)の1つを使ってキャストされることができます。
This example uses the conditional downcast operator (as?
) to conditionally cast the s
constant declared above to an instance of Swift’s String
type.
この例は、条件ダウンキャスト演算子(as?
)を使って、上で定義されるs
定数をSwiftのString
型へ条件付きでキャストします。
if let message = s as? String {
print("Successful cast to String: \(message)")
}
// Prints "Successful cast to String: This is a bridged string."
If you have prior knowledge that an Any
instance has a particular type, you can use the unconditional downcast operator (as!
). Performing an invalid cast triggers a runtime error.
あなたがAny
インスタンスがある特定の型を持つという事前の知識を持つならば、無条件のダウンキャスト演算子(as!
)を使うことも可能です。不正なキャストを行うことは実行時エラーの引き金になります。
let message = s as! String
print("Successful cast to String: \(message)")
// Prints "Successful cast to String: This is a bridged string."
let badCase = v as! String
// Runtime error
Casting is always safe in the context of a switch
statement.
キャストはswitch
文の文脈においては常に安全です。
let mixedArray: [AnyObject] = [s, v]
for object in mixedArray {
switch object {
case let x as String:
print("'\(x)' is a String")
default:
print("'\(object)' is not a String")
}
}
// Prints "'This is a bridged string.' is a String"
// Prints "'100' is not a String"
Accessing Objective-C Methods and Properties Objective-Cのメソッドやプロパティへのアクセス
When you use Any
as a concrete type, you have at your disposal every @objc
method and property—that is, methods and properties imported from Objective-C or marked with the @objc
attribute. Because Swift can’t guarantee at compile time that these methods and properties are actually available on an Any
instance’s underlying type, these @objc
symbols are available as implicitly unwrapped optional methods and properties, respectively.
あなたがAny
を具体的な型として使うとき、すべての@objc
メソッドやプロパティ — すなわち、Objective-Cからインポートされるか、@objc
属性で印されるメソッドとプロパティ — があなたの自由になります。SwiftはそれらのメソッドやプロパティがAny
インスタンスの下に横たわる型で実際に利用可能であるとコンパイル時に保証しないため、これら@objc
シンボルは暗黙的にアンラップされるオプショナルのメソッドやプロパティとしてそれぞれ利用可能です。
This example defines an Integer
type with an @objc
method named get
.
この例はInteger
型を、@objc
メソッドでget
と名付けられるものと共に定義します。
class IntegerRef {
let value: Int
init(_ value: Int) {
self.value = value
}
@objc func getIntegerValue() -> Int {
return value
}
}
func getObject() -> AnyObject {
return IntegerRef(100)
}
let obj: AnyObject = getObject()
In the example, obj
has a static type of Any
and a dynamic type of Integer
. You can use optional chaining to call the @objc
method get
on obj
safely. If you’re sure of the dynamic type of obj
, you can call get
directly.
例において、obj
はAny
の静的型とInteger
の動的型を持ちます。あなたは、オプショナル連鎖を使って、@objc
メソッドget
をobj
上で安全に呼び出すことができます。あなたがobj
の動的型に確信を持つならば、あなたはget
を直接に呼び出すこともできます。
let possibleValue = obj.getIntegerValue?()
print(possibleValue)
// Prints "Optional(100)"
let certainValue = obj.getIntegerValue()
print(certainValue)
// Prints "100"
If the dynamic type of obj
doesn’t implement a get
method, the system returns a runtime error when you initialize certain
.
obj
の動的型がget
メソッドを実装しないならば、システムは実行時エラーをあなたがcertain
を初期化する時に返します。
Alternatively, if you need to test whether obj
exists, use optional binding before calling the method.
あるいは、あなたがobj
が存在するかテストする必要があるならば、オプショナル束縛をそのメソッドを呼び出す前に使ってください。
if let f = obj.getIntegerValue {
print("The value of 'obj' is \(f())")
} else {
print("'obj' does not have a 'getIntegerValue()' method")
}
// Prints "The value of 'obj' is 100"