1
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 1 year has passed since last update.

初めてのSwift標準入力の受け取り方編!(!を使う理由調べてみた)

Last updated at Posted at 2023-08-15

Swiftをやる目的

・エンジニアになりたいきっかけが手持ちの洋服を管理できるアプリを作りたいと思ったから。
・iPhoneユーザーなので端末に自分のアプリがあればモチベが上がると思ったから。
・アプリを開発できれば、就活に活かせるポートフォリオを用意できると思ったから。

”let”と”var”の変数の使い分け

    - var(Variable - 意味/変数)
        - 再代入可能
    - let(let it beのlet説 - 意味/そのままにしておく)
        - 再代入不可

Swiftの標準入力の受け取り方-文字列-

let name = readLine()!
print("Hello \(name)")

標準入力
World
標準出力
Hello World

Swiftの標準入力の受け取り方-整数-

var number = Int(readLine()!)!
print(number)
number = 100
print(number)

標準入力
1
標準出力
1
100
・letを使って再代入した時のコンパイルエラーの例

let number = Int(readLine()!)!
print(number)
number = 100
print(number)

標準入力
1
標準出力
Main.swift:3:1: error: cannot assign to value: 'number' is a 'let' constant
number = 100
^~~~~~
Main.swift:1:1: note: change 'let' to 'var' to make it mutable
let number = Int(readLine()!)!
^~~
var

Swiftの ! (ここ更新するかも)

結果
・Swiftの ! はオプショナル型の値を取り出す記号で、変数から値(文字や数字)を取り出すときに必要な演算子。
・変数に値が入っていないと予期せぬ値が入り込んで安全に変数を使うことができないから!が必要。

理解までの道のり
・Swiftの ! は、アンラップ演算子(Unwrapping Operator)という。
・アンラップ演算子はオプショナル型(Optional)から値を取り出すために使用される。
・オプショナル型は、値が存在するかどうか不確かな状態を表すからそのままでは値を使用することができない。
・アンラップ演算子を使うことで、オプショナル型の値を安全に取り出して使用することができる。
・アンラップ演算子をオプショナル型の変数やプロパティの後に置くことで、その値が存在することが確定している場合に値を取り出すことができる。
・オプショナル型の値が nil(存在しないことを表す特殊な値)だった場合、アンラップ時にランタイムエラーが発生する可能性があるため、アンラップする前に必ず値が存在するかどうかを確認する必要がある。

1
0
1

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
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?