Help us understand the problem. What is going on with this article?

Swift as!について

More than 3 years have passed since last update.

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     // エラー

以上

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away