すらぼうの開発ノート

モバイルアプリエンジニアのメモ

【Swift】Cocoa Touch ClassとSwift Fileの違い

Xcodeで新しいファイルを作成する際に、いくつかの選択肢がある。

その際に「Swift File」と「Cocoa Touch Class」というものが表示される。

この2種類のファイルの違いについて説明する。

違い

「デフォルトの状態で何が書かれているか」が異なる。どちらも.swiftファイルである点は共通である。

  • Swift File
    • Foundationがimportされている
  • Cocoa Touch Class
    • subClassに指定したクラスが継承されているクラス
    • overrideが必要なメソッドが用意されている

なので使い分けとしては以下のようなイメージ。

  • Swift File
    • UI以外のロジックなどを記述する
  • Cocoa Touch Class
    • UIと紐付けるView Controllerを記述する

念の為それぞれを作成するとどのようなファイルが生成されるかを以下に示す。

Swift File

//
//  test1.swift
//  Flash Chat iOS13
//
//  Created by [your name] on 2023/10/08.
//  Copyright © 2023 Angela Yu. All rights reserved.
//

import Foundation

Cocoa Touch Class

サブクラスにUIViewControllerを指定した場合、以下のようになる。

//
//  ViewController.swift
//  Flash Chat iOS13
//
//  Created by [your name] on 2023/10/08.
//  Copyright © 2023 Angela Yu. All rights reserved.
//

import UIKit

class [file name]: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}