SwiftのAPIに関する基本的なガイドラインを100個以上ご紹介します。各APIやパターンにはそれぞれ特有の利用目的と実例があり、開発において非常に便利です。特に高度な機能や複雑なAPIには詳細な説明も加えました。この情報がSwift開発において役立つかも。

Int | Apple Developer Documentation
A signed integer value type.
SwiftのAPI: 開発者が知っておくべき100の重要な関数とライブラリ
文字列操作
String- 利用目的: 文字列の作成、操作。
- 例:
let str = String("Hello, World!")
String.prefix(_:)- 利用目的: 文字列の先頭から指定された数の文字を取得。
- 例:
let newStr = str.prefix(5) // "Hello"
String.suffix(_:)- 利用目的: 文字列の末尾から指定された数の文字を取得。
- 例:
let newStr = str.suffix(6) // "World!"
String.count- 利用目的: 文字列の長さを取得。
- 例:
let length = str.count // 13
String.isEmpty- 利用目的: 文字列が空かどうかを確認。
- 例:
let isEmpty = str.isEmpty // false
String.contains(_:)- 利用目的: 文字列が特定の文字列を含むかを確認。
- 例:
let doesContain = str.contains("World") // true
String.replacingOccurrences(of:with:)- 利用目的: 文字列内の特定の部分を別の文字列で置換。
- 例:
let replacedStr = str.replacingOccurrences(of: "World", with: "Universe") // "Hello, Universe!"
String.split(separator:)- 利用目的: 文字列を特定の区切り文字で分割。
- 例:
let array = str.split(separator: " ") // ["Hello,", "World!"]
String.joined(separator:)- 利用目的: 文字列の配列を連結。
- 例:
let joined = array.joined(separator: "-") // "Hello,-World!"
String.trimmingCharacters(in:)- 利用目的: 文字列から指定した文字セットを削除。
- 例:
let trimmed = str.trimmingCharacters(in: .whitespaces) // "Hello,World!"
数学・数値操作
Int/Float/Double- 利用目的: 整数や浮動小数点数を表現。
- 例:
let integer = Int(10); let floating = Float(10.5); let double = Double(10.5)
abs(_:)- 利用目的: 絶対値を取得。
- 例:
let absolute = abs(-10) // 10
min(_:_:)/max(_:_:)- 利用目的: 最小値または最大値を取得。
- 例:
let minimum = min(10, 20) // 10; let maximum = max(10, 20) // 20
pow(_:_:)- 利用目的: 累乗計算。
- 例:
let result = pow(2, 3) // 8
sqrt(_:)- 利用目的: 平方根を計算。
- 例:
let result = sqrt(9) // 3
ceil(_:)/floor(_:)- 利用目的: 切り上げ、切り捨て。
- 例:
let ceilResult = ceil(10.5) // 11; let floorResult = floor(10.5) // 10
round(_:)- 利用目的: 四捨五入。
- 例:
let rounded = round(10.5) // 11
sin(_:)/cos(_:)/tan(_:)- 利用目的: 三角関数。
- 例:
let sine = sin(90) // 1; let cosine = cos(0) // 1; let tangent = tan(45) // 1
arc4random_uniform(_:)- 利用目的: 乱数生成。
- 例:
let random = arc4random_uniform(10) // 0~9
remainder(dividingBy:)- 利用目的: 余りを計算。
- 例:
let remainder = 10.remainder(dividingBy: 3) // 1
データ構造
Array- 利用目的: 順序付きのコレクション。
- 例:
let array = [1, 2, 3]
Set- 利用目的: 順序なし、重複なしのコレクション。
- 例:
let set = Set([1, 2, 3])
Dictionary- 利用目的: キーと値のペアでデータを格納。
- 例:
let dict = ["key": "value"]
Tuple- 利用目的: 複数の値を一つにまとめる。
- 例:
let tuple = (10, "hello")
Optional- 利用目的: 値が存在するかどうかを表現。
- 例:
let optional: Int? = nil
Range/ClosedRange- 利用目的: 範囲を表現。
- 例:
let range = 1..<5 // 1 to 4; let closedRange = 1...5 // 1 to 5
Array.append(_:)- 利用目的: 配列に要素を追加。
- 例:
array.append(4) // [1, 2, 3, 4]
Array.remove(at:)- 利用目的: 配列から要素を削除。
- 例:
array.remove(at: 0) // [2, 3]
Set.insert(_:)- 利用目的: セットに要素を追加。
- 例:
set.insert(4) // {1, 2, 3, 4}
Dictionary.updateValue(_:forKey:)- 利用目的: 辞書の値を更新。
- 例:
dict.updateValue("new_value", forKey: "key") // ["key": "new_value"]
ファイル・ディレクトリ操作
FileManager- 利用目的: ファイルやディレクトリの操作。
- 例:
let fileManager = FileManager.default
FileManager.fileExists(atPath:)- 利用目的: ファイルまたはディレクトリが存在するか確認。
- 例:
fileManager.fileExists(atPath: "path/to/file")
FileManager.createDirectory(at:withIntermediateDirectories:attributes:)- 利用目的: ディレクトリの作成。
- 例:
fileManager.createDirectory(at: URL(string: "path/to/directory")!, withIntermediateDirectories: true, attributes: nil)
FileManager.contents(atPath:)- 利用目的: ファイルの内容を取得。
- 例:
let data = fileManager.contents(atPath: "path/to/file")
FileManager.moveItem(at:to:)- 利用目的: ファイルまたはディレクトリの移動。
- 例:
fileManager.moveItem(at: URL(string: "path/to/old")!, to: URL(string: "path/to/new")!)
FileManager.copyItem(at:to:)- 利用目的: ファイルまたはディレクトリのコピー。
- 例:
fileManager.copyItem(at: URL(string: "path/to/source")!, to: URL(string: "path/to/destination")!)
FileManager.removeItem(at:)- 利用目的: ファイルまたはディレクトリの削除。
- 例:
fileManager.removeItem(at: URL(string: "path/to/file")!)
FileManager.contentsOfDirectory(atPath:)- 利用目的: ディレクトリ内のアイテム一覧を取得。
- 例:
let items = try? fileManager.contentsOfDirectory(atPath: "path/to/directory")
FileManager.attributesOfItem(atPath:)- 利用目的: ファイルまたはディレクトリの属性を取得。
- 例:
let attributes = try? fileManager.attributesOfItem(atPath: "path/to/file")
FileManager.createFile(atPath:contents:attributes:)- 利用目的: 新しいファイルを作成。
- 例:
fileManager.createFile(atPath: "path/to/file", contents: Data(), attributes: nil)
ネットワーク操作
URLSession- 利用目的: HTTPリクエストを送信。
- 例:
let session = URLSession.shared
URLSession.dataTask(with:completionHandler:)- 利用目的: HTTP GETリクエストを送信し、レスポンスを取得。
- 例:
let task = session.dataTask(with: URL(string: "https://api.example.com")!) { data, response, error in // Handle response } task.resume()URLSession.uploadTask(with:from:completionHandler:)- 利用目的: ファイルをアップロード。
- 例:
let task = session.uploadTask(with: URLRequest(url: URL(string: "https://api.example.com/upload")!), from: Data()) { data, response, error in // Handle response } task.resume()URLComponents- 利用目的: URLの構築。
- 例:
var components = URLComponents() components.scheme = "https" components.host ="api.example.com" components.path = "/endpoint"URLRequest- 利用目的: HTTPリクエストの設定。
- 例:
var request = URLRequest(url: URL(string: "https://api.example.com")!) request.httpMethod = "GET"HTTPURLResponse- 利用目的: HTTPレスポンスの解析。
- 例:
if let httpResponse = response as? HTTPURLResponse { print(httpResponse.statusCode) }JSONSerialization- 利用目的: JSONデータの解析や生成。
- 例:
let json = try? JSONSerialization.jsonObject(with: data!, options: [])WebSocket- 利用目的: WebSocket通信。
- 難易度: 中 – 高
- 詳細: リアルタイム通信が必要な場合に使用します。WebSocketライブラリを使うことで、サーバとの双方向通信が可能です。
Alamofire(サードパーティ)- 利用目的: HTTPリクエストの送信。
- 難易度: 中
- 詳細: AlamofireはSwiftで書かれたHTTPネットワーキングライブラリで、URLSessionのラッパーとして機能します。より簡単にHTTPリクエストを行えます。
Moya(サードパーティ)- 利用目的: APIの抽象化とテスト。
- 難易度: 高
- 詳細: MoyaはAlamofireの上に構築され、API呼び出しを抽象化し、テスタビリティを向上させます。
データベース操作
UserDefaults- 利用目的: キー-値ペアの保存。
- 例:
UserDefaults.standard.set("value", forKey: "key")
Core Data- 利用目的: データの永続化。
- 難易度: 高
- 詳細: オブジェクトグラフをディスクに保存できる高度なAPIです。
Realm(サードパーティ)- 利用目的: データベース操作。
- 難易度: 中 – 高
- 詳細: SQLiteやCore Dataの代わりに使用できるモバイルデータベース。
SQLite- 利用目的: ローカルデータベース。
- 例:
import SQLite3 var db: OpaquePointer? sqlite3_open("path/to/database", &db)Firebase Realtime Database(サードパーティ)- 利用目的: リアルタイムデータベース。
- 難易度: 中
- 詳細: GoogleのFirebaseプラットフォームの一部。リアルタイムでデータを同期できます。
Firebase Firestore(サードパーティ)- 利用目的: ドキュメントベースのデータベース。
- 難易度: 中
- 詳細: Realtime Databaseよりも柔軟なクエリが可能。
CloudKit- 利用目的: iCloud上でデータを保存。
- 難易度: 中 – 高
- 詳細: AppleのiCloudサービスと連携したデータベースサービス。
NSFetchRequest- 利用目的: Core Dataのデータ検索。
- 例:
let request = NSFetchRequest<NSManagedObject>(entityName: "Entity") let results = trycontext.fetch(request)NSFetchedResultsController- 利用目的: Core DataのデータをUITableViewやUICollectionViewで使用。
- 難易度: 中
- 詳細: UITableViewやUICollectionViewのデータソースとして使用でき、データが変更されたときに自動的にビューが更新されます。
Plist- 利用目的: 設定やデータを保存。
- 例:
if let path = Bundle.main.path(forResource: "Data", ofType: "plist"), let xml =FileManager.default.contents(atPath: path), let plistData = try?PropertyListSerialization.propertyList(from: xml, options: .mutableContainersAndLeaves, format: nil) { // Use plistData }
UIコンポーネント
UILabel- 利用目的: テキストの表示。
- 例:
let label = UILabel(); label.text = "Hello"
UIButton- 利用目的: ボタンの表示とイベント処理。
- 例:
let button = UIButton(); button.setTitle("Click Me", for: .normal)
UIImageView- 利用目的: 画像の表示。
- 例:
let imageView = UIImageView(image: UIImage(named: "image.jpg"))
UITextField- 利用目的: テキスト入力。
- 例:
let textField = UITextField(); textField.placeholder = "Enter text"
UITableView- 利用目的: リストの表示。
- 例:
let tableView = UITableView()
UICollectionView- 利用目的: グリッド形式のリスト表示。
- 例:
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
UIScrollView- 利用目的: スクロール可能な領域の提供。
- 例:
let scrollView = UIScrollView()
UIActivityIndicator- 利用目的: ローディングインジケータの表示。
- 例:
let spinner = UIActivityIndicatorView(style: .medium); spinner.startAnimating()
UIAlertController- 利用目的: アラートダイアログの表示。
- 例:
let alert = UIAlertController(title: "Alert", message: "This is an alert.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default)) present(alert, animated: true)UIPageControl- 利用目的: 複数ページのインジケータ表示。
- 例:
let pageControl = UIPageControl(); pageControl.numberOfPages = 5
マルチスレッド・非同期処理
DispatchQueue- 利用目的: 非同期処理。
- 例:
DispatchQueue.global().async { // Background thread DispatchQueue.main.async { // Main thread } }OperationQueue- 利用目的: 非同期オペレーション。
- 例:
let queue = OperationQueue()
DispatchGroup- 利用目的: 複数の非同期タスクの完了を待つ。
- 例:
let group = DispatchGroup() group.enter() // Task 1 group.leave() group.enter() // Task 2 group.leave() group.notify(queue: .main) { // All tasks completed }DispatchSemaphore- 利用目的: リソースの同時アクセス制限。
- 例:
let semaphore = DispatchSemaphore(value: 1) semaphore.wait() // Critical sectionsemaphore.signal()NSThread- 利用目的: 低レベルのスレッド操作。
- 例:
let thread = Thread(target: self, selector: #selector(self.method), object: nil); thread.start()
NSRunLoop- 利用目的: イベントループの制御。
- 例:
RunLoop.main.run()
Timer- 利用目的: タイマー処理。
- 例:
let timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)
async/await(Swift 5.5+)- 利用目的: 非同期処理の簡易化。
- 例:
async func fetchData() -> Data { // ... } let data = await fetchData()Task(Swift 5.5+)- 利用目的: 非同期タスクの管理。
- 例:
Task { let data = await fetchData() }GCD (Grand Central Dispatch)- 利用目的: 非同期処理と並行処理。
- 例:
DispatchQueue.global(qos: .background).async { // Do something }
デバイス機能
CLLocationManager- 利用目的: 位置情報の取得。
- 例:
let locationManager = CLLocationManager()
CMMotionManager- 利用目的: 加速度センサー、ジャイロスコープのデータ取得。
- 例:
let motionManager = CMMotionManager()
AVFoundation- 利用目的: オーディオとビデオの操作。
- 例:
import AVFoundation
UIImagePickerController- 利用目的: カメラやフォトライブラリへのアクセス。
- 例:
let picker = UIImagePickerController()
LocalAuthentication- 利用目的: Touch IDやFace IDでの認証。
- 例:
import LocalAuthentication
Push Notification- 利用目的: プッシュ通知の送受信。
- 例:
import UserNotifications
CoreBluetooth- 利用目的: Bluetoothデバイスとの通信。
- 例:
import CoreBluetooth
HealthKit- 利用目的: 健康データの取得と保存。
- 例:
import HealthKit
MapKit- 利用目的: 地図の表示と操作。
- 例:
import MapKit
CoreML- 利用目的: 機械学習モデルの実行。
- 例:
import CoreML
デバッグ・テスト
print(_:separator:terminator:)- 利用目的: コンソールへの出力。
- 例:
print("Hello, World!")
assert(_:message:file:line:)- 利用目的: アサーションの使用。
- 例:
assert(x > 0, "x should be positive")
XCTest- 利用目的: ユニットテスト。
- 例:
import XCTest
Debug- 利用目的: デバッグビルドでのみコードを実行。
- 例:
#if DEBUG // Debug-only code #endifos_log- 利用目的: ロギング。
- 例:
import os.log os_log("This is a log message.")dump(_:)- 利用目的: オブジェクトの内容を詳細に出力。
- 例:
dump(object)
Mirror- 利用目的: リフレクション。
- 例:
let mirror = Mirror(reflecting: object)measure(_:)in XCTest- 利用目的: パフォーマンステスト。
- 例:
measure { // Code to measure }Simulator- 利用目的: iOSデバイスのシミュレーション。
- 例: Xcode内でiOS Simulatorを起動。
lldbCommands- 利用目的: デバッガコマンド。
- 例:
po,bt,frameなどのlldbコマンド。
デザインパターン
Singleton- 利用目的: シングルトンインスタンスの作成。
- 例:
class Singleton { static let shared = Singleton() private init() {} }Observer- 利用目的: オブザーバーパターンの実装。
- 例:
NotificationCenter
MVC- 利用目的: Model-View-Controllerアーキテクチャ。
- 例: UIKitアプリケーション。
MVVM- 利用目的: Model-View-ViewModelアーキテクチャ。
- 例: SwiftUIアプリケーション。
Decorator- 利用目的: クラスの機能を拡張。
- 例:
protocol Coffee { func cost() -> Double }Strategy- 利用目的: アルゴリズムの交換。
- 例:
protocol SortingStrategy { func sort(_ array: [Int]) -> [Int] }Factory Method- 利用目的: オブジェクト生成の抽象化。
- 例:
protocol Animal { func makeSound() }Composite- 利用目的: オブジェクトのグルーピング。
- 例:
protocol Shape { func draw() }Command- 利用目的: アクションのカプセル化。
- 例:
protocol Command { func execute() }State- 利用目的: 状態管理の抽象化。
- 例:
protocol State { func handle(context: Context) }


コメント