Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
88
Help us understand the problem. What is going on with this article?
@suisuina

Swift as!について

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

以上

88
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  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
suisuina
Technical director,engineer

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
88
Help us understand the problem. What is going on with this article?