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

【Swift】定数と変数の使い方

Posted at

概要

Swiftの学習中の備忘録です。
基本の基本、変数と定数の使い方についてまとめています。

筆者環境

  • MacBook Pro (13-inch, 2019)
  • macOS Catalina(Version 10.15.4)
  • Xcode(Version 11.4)
  • Swift5.2

定数 let

定数は定義した初期値を”後から上書きすることがないもの”に使います。
不意にデータの書き換えが行われないように、
基本的には定数を使い、上書きが必要な値のみ変数で定義するのがいいようです。


let msg: String = "Hello!" 
//String型(データ型)のmsg(定数名)に"Hello!"(初期値)を代入

let msg = "Hello!"
//データ型を省略して書くことも出来る(型推論)

上書きしようとするとエラーが出る。


let msg = "Hello!"
msg = "Good Bye!"

//エラー文
Immutable value 'msg' may only be initialized once
//不変の値である"msg"は一度しか初期化できない(変更できない)。

変数 var

定数は定義した初期値を”後から変更する可能性のあるもの”に使います。


var msg: String = "Hello!" 
//String型(データ型)のmsg(定数名)に"Hello!"(初期値)を代入

var msg = "Hello!"
//データ型を省略して書くことも出来る(型推論)

定数と違い、上書き出来る。


var msg = "Hello!"
msg = "Good Bye!"

print(msg)
// Good Bye!

最後に

以上、簡単ですが定数と変数の使い方についてでした。
学習を進める中で、追加したい内容が出てきたら都度追記していきます。

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?