0
1

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.

Subscriptとは

Posted at

SubScript

Swiftでよく見るsubscriptとはいったいなんだろう?と思ったので調べてみた。

Subscriptは定数やEnum,クラス、構造体などにアクセスすると 配列で辞書型でデータを取得したようにデータを隠すために使用される。
日本語で言うと添字になる。配列の要素にそれぞれ割り振られた番号のこと。

例コード

 class Fish {

  var fishNames = [String]()  
    init() {
 fishNames = []
}
   subscript(index: Int) -> String {
        get {
            return fishNames[index]
        }
        set(name) {
            fishNames.insert(name, atIndex: index)
        }
    }
}

要は、getterとsetterの仕組みになっている。開発者が添字にアクセスすることでsubscriptの引数にその数字が入る。
辞書型でも使えるのでInt型ではなくString型でも大丈夫。

class Fish {
	subscript( s : String  ) -> String {
		return "美味しい, \(s)!"
	}
}

var f = Fish()
print( f[ "🐠" ] )美味しい🐠
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?