Overview 概要
In Objective-C, the id
type represents objects that are instances of any Objective-C class. The id
type is instead imported by Swift as the Any
type. When you pass a Swift instance to an Objective-C API, it's bridged as an id
parameter so that it's usable in the API as an Objective-C object. When id
values are imported into Swift as Any
, the runtime automatically handles bridging back to either class references or value types.
Objective-Cでは、id
型は、何らかのObjective-Cクラスのインスタンスであるオブジェクトを表します。id
型は、代わりにSwiftによってAny
型としてインポートされます。あなたがSwiftインスタンスをあるObjective-C APIに渡す場合、それはid
パラメータとしてブリッジされます、それでそれはそのAPIにおいてObjective-Cオブジェクトとして利用可能です。id
値がスウィフトへAny
としてインポートされる時、ランタイムはクラス参照または値型のどちらかへの逆のブリッジを自動的に取り扱います。
Downcast Objects to Call Methods and Access Properties オブジェクトをダウンキャストしてメソッドの呼び出しおよびプロパティにアクセスする
When you work with objects of type Any
where you know the underlying type, it's often useful to downcast those objects to the underlying type. However, because the Any
type can refer to any type, a downcast to a more specific type isn't guaranteed by the compiler to succeed.
あなたが基盤型を知っているところの型Any
のオブジェクトを扱う場合、しばしば役立つのはそれらオブジェクトを基盤型へとダウンキャストすることです。しかしながら、Any
型がどんな型でも参照できることから、より具体的な型へのダウンキャストはコンパイラによって成功することが保証されません。
You can use the conditional type cast operator (as?
), which returns an optional value of the type you are trying to downcast to:
あなたは、条件付き型キャスト演算子(as?
)を使うことができます、それはあなたがそれへとダウンキャストを試みる型のオプショナル値を返します:
If you're completely certain about the type of the object, you can use the forced downcast operator (as!
) instead.
あなたがオブジェクトの型について完全に確信しているならば、あなたは強制ダウンキャスト演算子(as!
)を代わりに使うことができます。
However, if a forced downcast fails, a runtime error is triggered: しかしながら、強制型キャストが失敗するならば、実行時エラーが引き起こされます: