0
0

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 5 years have passed since last update.

The Basic - Constants and Variables

Last updated at Posted at 2017-02-09

参考

The Swift Programming Language 3.0.1
The Basic - Constants and Variables

定数と変数

Swift では値を格納する際 定数(Constants)変数(Variables) を使う。

定数は、一度格納した値は変更できず、変数は何度でも変更できる。
プログラムを通して値の変更が無いことがわかっている場合は出来るだけ定数を使う。

定数・変数の命名規則

Swiftでは定数・変数名に記号、絵文字、全角文字が使えるが一般的に言って面倒の原因になるようなので、半角英数字を使う。
その上で自分流の規則は

  • 最初の一文字目は英小文字
  • 二文字目以降には半角数字が使える
  • キャメルケースで記述する

宣言

定数・変数は利用する前に宣言しておく必要がある。それぞれにキーワードがあり、定数は let 変数は var で宣言する

// 定数の宣言
let sampleConstant = 1

// 変数の宣言
var sampleVariable = 2

カンマ区切りにすることで複数を1行で同時に宣言できる

let sampleA = 1, sampleB = 2
var sampleC = 3, sampleD = 4

Swift では値に 型(types) の概念がある。
定数・変数はそれぞれが型を持ち、その型にあてはまる値しか格納できない。

型簡易一覧

Swift で使える型の簡易一覧。このほかにもあるらしい。

型名 内容
Int 整数、1, 2, 3, 10, 100, -1, -2, -100 など
Double 小数点、1.0, 3.14, -1.0, -3.14 など
String 文字列、" "でくくる。"yes", "hello"など
Bool 真偽、true もしくは false

型推測

定数・変数を宣言する際にリテラル値をあてておくと、その値種類から自動的に型を推測して決めてくれる。

// sampleVariable の値が 1 であることから、自動的に型は Int となり、小数点や文字列は受け入れなくなる
var sampleVariable = 1

型の指定

型を明示的に指定したい場合は、定数・変数宣言時に型名を明示する。

let stringConstant: String = "abc"

型を指定しつつ複数の定数・変数を宣言する

同じ型ならば、定数・変数名をカンマで区切って一度に宣言できる。

var varA, varB, varC: String
0
0
2

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?