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?

Swift : 初学者が絶対に押さえておきたい基本文法

Posted at

今回は、Swiftを初めて学ぶ方向けに絶対に押さえておきたい基本文法をまとめてみました。
まずは、変数・定数から始まり、条件分岐・ループ・関数・Optionalといった基礎を一通り紹介します!必ず抑えておきましょう!!

変数と定数

var name = "Tanaka"   // 変数(値を変更できる)
let age = 20         // 定数(値は変更不可)
  • var は変更可能
  • let は変更不可

型推論が使えるが、型を明示することも可能

データ型

  • Int:整数

  • Double / Float:小数

  • String:文字列

  • Bool:真偽値(true/false)

  • Array / Dictionary:配列・辞書

let scores: [Int] = [80, 90, 100]
let student: [String: String] = ["name": "Taro", "grade": "A"]

条件分岐

// if文
let score =85

if score >= 90 {
    print("素晴らしい!")
} else if score >= 60 {
    print("良い!")
} else {
    print("また頑張ろう!")
}

// switch文
switch score {
case 90...100:
    print("素晴らしい!")
case 60..<90:
   print("良い!")
default:
    print("また頑張ろう!")
}

ループ

// for文
for i in 1...5 {
    print(i)
}

// while文
var n = 0
while n < 5 {
    print(n)
    n += 1
}

// 配列ループ
let fruits = ["りんご", "バナナ", "オレンジ"]
for fruit in fruits {
    print(fruit)
}

関数

func greet(name: String) -> String {
    return "こんにちは, \(name)!"
}
print(greet(name: "Taro"))

  • func で関数を定義

  • 引数と戻り値の型を指定

  • 文字列補間で変数を簡単に埋め込める

Optional(値があるかないか)

var nickname: String? = "Taro"
print(nickname)        

// 安全に取り出す
if let name = nickname {
    print(name)
}
  • ? は値がnilかもしれないことを表す

  • if let や guard let で安全にアンラップ

まとめ

  • 押さえるべき基本文は「変数と定数」「データ型」「条件分岐」「ループ」「関数」「Optional」等だと思います!
  • その中で特に Optional(値があるかもしれない / ないかもしれない) はSwiftの特有なものなので、慣れが必要感もしれないです!

以上、学者が絶対に押さえておきたい基本文法でした!是非参考にしてみてください!🙌

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