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

Struct と Class の使い分けを簡単に説明してみました!(初心者向け)

Posted at

Swiftでは

  • 構造体(struct)

  • クラス(class)

の2つでオブジェクトを定義できますが、使い分けには明確な違いがあります。
今回は使い分けの基準を簡単に説明していきたいと思います!

使い分けの基準

structを使うべき場面

  • データの入れ物として使いたいとき

  • 値渡しの方が直感的なとき

  • イミュータブルなデータを扱いたいとき

  • 他の型に継承させる予定がないとき

例: モデル(User, Productなど)で変化しないデータ

struct User {
    let name: String
    let age: Int
}

Class を使うべき場面

オブジェクト同士で共有したい状態があるとき

継承して機能を拡張する必要があるとき

例:
管理クラス(ViewModel)

class NetworkManager {
    var isConnected: Bool = false
    
    func connect() {
        isConnected = true
    }
}

まとめ

使い分けまとめ
Struct 値型・コピー・軽量データ向き
Class 参照型・共有向き

以上StructClass の使い分けでした!、ぜひ参考にしてみてください!✌️

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