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

【Swift】アクセス修飾子

Last updated at Posted at 2024-11-10

概観

【緩い】open > public > internal(デフォルト) > fileprivate > private【厳しい】

open public internal filelprivate private
同じ型の中でアクセス
同じファイル内の他の型からアクセス
同じモジュール内の他のファイルからアクセス
異なるモジュールからアクセス
異なるモジュールでのoverrideやサブクラス化

モジュール:コードを配布する単位

  • ライブラリ
  • フレームワーク(バイナリコードに加えて画像などのリソースもひとまとめになったもの)
  • アプリ本体(.appファイル)

fileprivate

fileprivate:ファイルレベルでの隠蔽を提供しつつ、同じファイル内での柔軟な実装を可能にできる。

CustomView.swift
class CustomView: UIView {
    // 完全に内部実装として隠蔽したい状態
    private var internalState = false
    
    // 同じファイル内の他の型(例:デリゲート)と共有したい状態
    fileprivate var sharedState = false
    
    private func updateInternalState() {
        internalState = true
    }
}

// 同じファイル内のデリゲート
protocol CustomViewDelegate {
    func didUpdateState(_ view: CustomView)
}

class CustomViewDelegateImpl: CustomViewDelegate {
    func didUpdateState(_ view: CustomView) {
        print(view.sharedState)    // OK - fileprivateなのでアクセス可能
        print(view.internalState)  // コンパイルエラー - privateなのでアクセス不可
    }
}

getter/setterで制限を変える

// 書き込みはprivate
// 読み取りはinternal
private(set) var id

// 書き込みはprivate
// 読み取りはpublic
public private(set) var id
1
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
1
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?