LoginSignup
2
3

More than 3 years have passed since last update.

Swiftのstatic (初歩的)

Posted at

この記事はstaticの使い方を簡単にまとめたもので、詳しい解説は明記されていません。

使い方

struct MyStructuer {
    let instanceProperty = "ABC"
    static let typeProperty = 123 //これだけ!!
}

変数などを定義する際に、直前にstaticをつけるだけです。

staticをつけた場合と、つけなかった場合の違いを見ていくと

struct MyStructuer {
    let instanceProperty = "ABC"
    static let typeProperty = 123 
}

mystructuer = MyStructuer() //インスタンスを生成
print(mystructuer.instanceProperty) //=> ABC
print(MyStructuer.typeProperty) //=> 123

どこが違うかというと、

staticをつけていない変数はMyStructuerクラスからインスタンスを生成し、そのインスタンスからプロパティを出力しています。
staticをつけている変数は、インスタンスは使わずにプロパティを出力しています。

これによってインスタンスを生成する手間が省け、どこからでも簡単にプロパティを呼び出すことができます。

しかし逆の操作はともにエラーになりますので注意してください。

print(MyStructuer.instanceProperty) //=> エラー
print(mystrctuer.typeProperty) //=> エラー

staticはクラスやメソッドにも同様にして使えるので、より快適なコードを目指して使いこなしたいですね!

2
3
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
2
3