Swift入門|iOSアプリ開発の第一歩

プログラミング言語

SwiftはAppleが開発したiOS・macOSアプリ開発の公式言語です。型安全性とシンプルな構文を両立しており、近年はサーバーサイド領域への展開も進んでいます。本記事では、Swiftの基本とiOSアプリ開発の第一歩を解説します。

Swiftの特徴

  • 型安全・型推論で堅牢
  • Optional型でnull安全
  • クラスと構造体(値型)を使い分け
  • 関数型と命令型の両スタイルが書ける
  • SwiftUIで宣言的UI、Combineで非同期データ流

環境構築

  • Mac + Xcode をインストール(App Store)
  • iOSアプリのテンプレートは「App」を選択し、Interface = SwiftUI
  • シミュレータで実機なしで動作確認可能

SwiftUIによる最小アプリ

import SwiftUI

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

struct ContentView: View {
    @State private var count = 0
    var body: some View {
        VStack {
            Text("Count: \(count)")
            Button("Increment") { count += 1 }
        }
        .padding()
    }
}

主要な構文

// 変数・定数
var name = "Alice"
let pi = 3.14

// Optional
var age: Int? = nil
if let a = age { print(a) }

// 構造体
struct User {
    let id: Int
    let name: String
}

// クラス + メソッド
class Counter {
    private(set) var value: Int = 0
    func increment() { value += 1 }
}

非同期処理(async/await)

func fetchUser(id: Int) async throws -> User {
    let (data, _) = try await URLSession.shared.data(
        from: URL(string: "https://api.example.com/users/\(id)")!
    )
    return try JSONDecoder().decode(User.self, from: data)
}

主要なフレームワーク

  • SwiftUI:宣言的UI(公式推奨)
  • UIKit:歴史ある命令的UI
  • Combine:リアクティブストリーム
  • Core Data / SwiftData:永続化
  • SwiftPM:パッケージ管理

アプリ公開の流れ

  • Apple Developer Program(年額)に登録
  • App Store Connectでアプリ情報入力
  • XcodeでArchive → App Store Connectにアップロード
  • 審査を経て公開

まとめ

SwiftはApple純正の最新言語で、SwiftUIによる宣言的UIで開発が大きくシンプルになっています。SwiftUI + async/await + SwiftDataがモダンスタックの中心。Macさえあれば無料でiOSアプリ開発を始められます。