LoginSignup
88

More than 5 years have passed since last update.

Swift as!について

Last updated at Posted at 2016-03-07

Swiftのas!について記載

asはクラスの型変換に使われますが、asとas!、as?との違いがあります。

as:キャストが成功すると保証されるときに使用(アップキャストなど)
as!:強制ダウンキャストの際に使用
as?:ダウンキャストが成功するか分からない場合に使用(失敗すると戻り値はnil)

class Car {}
class Bike: Car {}
class Track:Car {}

let a: Car = Bike()
a as Bike       //ダウンキャストではエラーが発生
a as! Bike      // 強制ダウンキャストは成功

let b = Bike()
b as Car        // 上位クラスへのアップキャストは成功

let c:Car = Bike()
c as? Track     // nilが返る
c as! Track     // エラー

以上

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
88