インスタンスが特定のサブクラス型であるかをチェックする型チェック演算子 (is
) を使用します。インスタンスがそのサブクラス型である場合には、型チェック演算子は true
を返し、そうでない場合には false
を返します。
次の例では、配列 library
にある Movie
と Song
のインスタンス数を保持する変数 movieCount
と songCount
を定義しています。
var movieCount = 0
var songCount = 0
for item in library {
if item is Movie {
movieCount += 1
} else if item is Song {
songCount += 1
}
}
print("Media library contains \(movieCount) movies and \(songCount) songs")
// "Media library contains 2 movies and 3 songs" と出力
この例は、配列 library
にあるすべてのアイテムを繰り返し処理しています。一巡ごとに、for
–in
ループは配列にある次の MediaItem
を定数 item
に設定します。
現在の MediaItem
が Movie
インスタンスの場合には、item is Movie
は true
を返し、そうでない場合には false
を返します。同じように、item is Song
はアイテムが Song
インスタンスかをチェックします。for
–in
ループの最後では、movieCount
と songCount
の値はそれぞれの型で見つかった MediaItem
のインスタンス数になります。
Portions of this page are translations based on work created and shared by Apple and used according to terms described in the Creative Commons Attribution 4.0 International License.