1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

どんな型でも代入できるAny型とは swift

Last updated at Posted at 2021-04-26

■Any型とは型の一つで何でも屋さん

IntでもStringでもなんの型も入る

■注意:: 中身取り出す時はオプショナルバインディングで取り出すと安全。

var a:Any = 123

//a as? Intで aはInt型と指定してる。 合っていたら
if let b = a as? Int {
   print(a)
}
//結果: 123

■Any型を指定した変数は後から違う型でも代入できる!!!

上の続き
普通に型推論でvar a = 123にして下記のように文字列型を入れるとエラーになる。
だがAny型やったらなんでも入るから新たに文字列型を入れれるんだよこれが!


a = "こんにちわ"
if let b = a as? String {
  print(b)
}
//結果: こんにちわ

1
4
0

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
1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?