Swift: Swiftの変数と定数:varとletの初心者向けガイド
変数は中身をいつでも入れ替えられるラベル付きの箱のようなもの。定数は一度封をしたら変更できない封印された箱のようなものです。このレッスンでは、Swiftでデータを保存する2つの主要な方法を学びます。
1. 学習目標
var(変数)とlet(定数)の違い- Swiftの型推論がデータ型を自動的に識別する仕組み
- 4つの基本データ型:Int、Double、String、Bool
- 型安全機構がコードエラーを防ぐ仕組み
- 異なる型間での値の変換
2. 実話:ECデータアナリストのケース
(1) 課題:数字とテキストを混在させてクラッシュ
AliceはECのデータアナリストで、毎日5万件以上の注文データを処理しています。彼女は商品��月次売上推移を追跡するコードを書きました:
var orderCount = "8500"
// Next month, orders grew by 1200
orderCount = orderCount + 1200 // Compilation error!
Swiftではテキストと数字の混在は許されません。Aliceのコードはコンパイルできませんでした。根本原因を見つけるのに30分かかりました——"8500"の引用符によって、Swiftがそれを数値(Int)ではなくテキスト(String)として扱っていたのです。
(2) 解決策:変数の型を正しく宣言する
宣言時の引用符を外すだけで、Swiftは8500が整数であることを正しく推論します:
// Correct data type definitions
var orderCount = 8500 // Int
var productName = "Headphones" // String
var unitPrice = 49.99 // Double
orderCount = orderCount + 1200
let totalRevenue = Double(orderCount) * unitPrice
print("Product: \(productName)")
print("Monthly sales: \(orderCount), Revenue: $\(totalRevenue)")
出力:
TEXT 📖 参照専用Product: Headphones Monthly sales: 9700, Revenue: $485003.0
(3) 結果:型を理解した後のコーディング効率
| 観点 | Before | After |
|---|---|---|
| 型関連エラー | 週5〜8回 | ほぼゼロ |
| 1件あたりのデバッグ時間 | 20〜30分 | 即座に特定 |
| コードの可読性 | StringとIntが混在 | 型が明確に区別できる |
| 型の理解度 | 「エラーが出たら引用符を追加」 | 「適切な型を自ら選択」 |
3. 変数と定数
Swiftではvarを変数(値の変更可)に、letを定数(代入後の値は固定)に使います。どちらを選ぶかは、データが変更される必要があるかどうかで決まります。
graph TB
A[データ保存] --> B["var 変数"]
A --> C["let 定数"]
B --> D[値を変更可能]
B --> E["var age = 25"]
B --> F["age = 26 ✅"]
C --> G[値を変更不可]
C --> H["let name = \"Alice\""]
C --> I["name = \"Bob\" ❌"]
| 特徴 | var 変数 |
let 定数 |
|---|---|---|
| 値の変更可否 | ✅ 再代入可能 | ❌ 不変 |
| ユースケース | カウンター、累計、一時データ | 固定設定、ユーザー名、数学定数 |
| コンパイラ最適化 | 通常 | インライン最適化の可能性あり |
| 推奨 | 必要な時のみ使用 | デフォルトで推奨 |
(1) 変数 — varで宣言
変数はプログラム実行中に変更されるデータを保存します:
// Variable values can be modified at any time
var score = 0
score = 85 // Update value
score = score + 10 // Recalculate based on current value
: Intと書く必要はありません。
(2) 定数 — letで宣言
定数は一度代入すると値を変更できません。letを使うことで、誤った変更によるバグを防げます:
// Constants cannot be modified after assignment
let maxLoginAttempts = 5
// maxLoginAttempts = 6 // ❌ Compilation error
let pi = 3.14159
let appName = "MyApp"
letを優先することを推奨しています。データを変更する必要がない場合は常にletで宣言しましょう——コードがより安全で理解しやすくなります。
▶ サンプル: ショッピングカートデータの管理
// ============================================
// Use variables for cart quantity, constants for product info
// ============================================
// Constants: Fixed information
let productName = "Wireless Headphones"
let unitPrice = 79.99
// Variable: Changing data
var quantity = 1
print("Product: \(productName)")
print("Unit price: $\(unitPrice)")
print("Current quantity: \(quantity)")
// User increased the purchase quantity
quantity = 3
let total = unitPrice * Double(quantity)
print("Buying \(quantity) items, Total: $\(total)")
出力:
TEXT 📖 参照専用Product: Wireless Headphones Unit price: $79.99 Current quantity: 1 Buying 3 items, Total: $239.97
4. 基本データ型
Swiftには4つのよく使われる基本データ型があり、それぞれ特定の形式のデータを保存します。変数や定数の型が一旦決まると、異なる型のデータを保存することはできません。
graph TB
A[基本データ型] --> B["Int 整数"]
A --> C["Double 浮動小数点"]
A --> D["String 文字列"]
A --> E["Bool ブール値"]
B --> F["42, -10, 0"]
C --> G["3.14, -0.5"]
D --> H["\"Hello\""]
E --> I["true / false"]
| 型 | 意味 | 例 | メモリ |
|---|---|---|---|
Int |
整数(正、負、ゼロ) | 42、-10、0 |
8バイト |
Double |
浮動小数点(小数) | 3.14、-0.5 |
8バイト |
String |
文字列 | "Hello"、"Swift" |
動的 |
Bool |
ブール値 | true、false |
1バイト |
(1) Int — 整数
Intは整数を保存します。64ビットデバイスでの範囲は約±9.2 × 10^18です:
let year = 2026
var count = -100
let population: Int = 8_000_000_000 // Underscores improve readability
(2) Double — 浮動小数点数
Doubleは小数点を含む数値を保存し、少なくとも15桁の10進精度を持ちます:
let temperature = 36.5
var price = 19.99
let taxRate = 0.08
IntとDoubleを直接演算で混在させることはできません。明示的な型変換が必要です。
(3) String — 文字列
Stringはテキストデータを保存し、ダブルクォートで囲みます:
let userName = "Alice"
var message = "Welcome to Swift"
let empty = "" // Empty string
(4) Bool — ブール値
Boolはtrueとfalseの2つの値のみを持ち、条件分岐に使用されます:
let isLoggedIn = false
var isAvailable = true
let isGreater = 10 > 5 // Comparison automatically produces true
▶ サンプル: ユーザー情報の型チェック
// ============================================
// Storing user information with different types
// ============================================
let userName = "Bob" // String
var age = 28 // Int
let height = 1.85 // Double
var isPremiumMember = false // Bool
print("Name: \(userName)")
print("Age: \(age)")
print("Height: \(height) m")
print("Member: \(isPremiumMember)")
// Type safety — the following line will not compile
// age = "twenty-eight" // ❌ Cannot assign String to Int
出力:
TEXT 📖 参照専用Name: Bob Age: 28 Height: 1.85 m Member: false
5. 型アノテーションと型変換
Swiftは型安全な言語です——すべての変数と定数の型はコンパイル時に決定されなければなりません。Swiftに型を推論させるか、手動で指定することができます。
(1) 明示的な型アノテーション
変数名または定数名の後にコロンと型名を追加して、明示的に型を指定します:
let name: String = "Charlie"
var age: Int = 25
var price: Double = 29.99
let isActive: Bool = true
| アプローチ | 構文 | 使用場面 |
|---|---|---|
| 型推論 | let name = "Alice" |
値から型が明らかな場合 |
| 型アノテーション | let name: String = "Alice" |
型の意図を明確にしたい場合、��期値が曖昧な場合 |
| 宣言だけ先にして後で代入 | var name: String → name = "Alice" |
宣言時に即座に代入できない場合 |
(2) 型変換
異なる型同士は直接演算や代入ができません——明示的な変換が必要です:
let apples = 3
let pricePerApple = 0.99
// let total = apples * pricePerApple // ❌ Int and Double cannot multiply directly
let total = Double(apples) * pricePerApple // ✅ Convert Int to Double
| 変換 | 意味 | 例 |
|---|---|---|
Int(value) |
整数に変換(小数切り捨て) | Int(3.14) → 3 |
Double(value) |
浮動小数点に変換 | Double(5) → 5.0 |
String(value) |
文字列に変換 | String(42) → "42" |
▶ サンプル: 注文合計額の計算
// ============================================
// Calculate order total, demonstrating type conversion
// ============================================
import Foundation
let itemCount = 5 // Int
let unitPrice = 12.99 // Double
let taxPercent = 0.08 // Double
// Int must be converted to Double for arithmetic
let subtotal = Double(itemCount) * unitPrice
let taxAmount = subtotal * taxPercent
let total = subtotal + taxAmount
print("Item count: \(itemCount)")
print("Unit price: $\(unitPrice)")
print("Subtotal: $\(subtotal)")
print("Tax (8%): $\(taxAmount)")
print("Total: $\(total)")
// Convert Double to String for text concatenation
let receipt = "Total: $" + String(format: "%.2f", total)
print(receipt)
出力:
TEXT 📖 参照専用Item count: 5 Unit price: $12.99 Subtotal: $64.95 Tax (8%): $5.196 Total: $70.146 Total: $70.15
6. 完全な例:注文統計サマリー
// ============================================
// E-commerce order statistics summary
// Demonstrates variables, constants, data types, type conversion
// ============================================
import Foundation
// 1. Constants: Store info and fixed configuration
let storeName = "Swift Gear Shop"
let taxRate = 0.07
// 2. Variables: Mutable order data
var orderCount = 0
var totalRevenue = 0.0
// 3. Process first batch of orders
let price1 = 49.99
let qty1 = 3
orderCount += qty1
let subtotal1 = Double(qty1) * price1
totalRevenue += subtotal1
// 4. Process second batch of orders
let price2 = 129.00
let qty2 = 1
orderCount += qty2
let subtotal2 = Double(qty2) * price2
totalRevenue += subtotal2
// 5. Output statistics report
print("Store: \(storeName)")
print("=== Sales Statistics ===")
print("Items sold: \(orderCount)")
print("Total revenue: $\(totalRevenue)")
print("Estimated tax: $\(totalRevenue * taxRate)")
print("Net revenue: $\(totalRevenue * (1 - taxRate))")
let summary = "Processed " + String(orderCount) + " items today"
print(summary)
出力:
TEXT 📖 参照専用Store: Swift Gear Shop === Sales Statistics === Items sold: 4 Total revenue: $278.97 Estimated tax: $19.5279 Net revenue: $259.4421 Processed 4 items today
❓ よくある質問
\(value)またはString()関数を使用して明示的に変換してください。var score: Intで宣言だけ先にして後で代入、またはlet value: Double = 5で5をIntではなくDoubleとして扱わせる場合。&+のようなオーバーフロー演算子も用意されており、特殊なケースを安全に処理できます。📖 まとめ
varを変数(値の変更可)に、letを定数(値の変更不可)に使用- Swiftは型推論によって型を決定するため、常に型アノテーションが必要なわけではない
- 4つの基本データ型:Int(整数)、Double(小数)、String(文字列)、Bool(true/false)
- Swiftは型安全な言語——異なる型を混在させたり暗黙的に変換したりできない
- 型変換には
Type(value)構文を使用(例:Double(3)は3.0を生成) letを優先し、値の変更が必要な場合のみvarを使用
📝 練習問題
- 初級: 定数
let city = "東京"と変数var population = 14_000_000を宣言し、printを使用して「東京の人口は14000000人です」と出力してください。 - 中級: 摂氏温度を保存するDouble変数を定義し、華氏に変換して(計算式: °F = °C × 9/5 + 32)、両方の単位で結果を出力してください。
- 上級: 通貨換算プログラムを作成してください。為替レート(1 USD = 0.92 EUR)を定数で保存し、ドル額を変数で保存してから、対応するユーロ額を計算して出力してください。Int、Double、Stringの少なくとも3つの型を使用する必要があります。