0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Swiftにおけるアクセス修飾子について

Last updated at Posted at 2021-07-21

・Swiftにおけるアクセス修飾子

・アクセス修飾子には、公開範囲が広い順に以下のものが用意されている。

・デフォルトはinternal

アクセス修飾子 アクセスレベル
open モジュール内外のすべてのアクセスを許可
public モジュール内外の全てのアクセスを許可するが、モジュール外ではクラスを継承したりオーバーライドしたりすることはできない
internal 同一モジュール内のアクセスのみを許可
fileprivate 同一ソースファイル内のアクセスのみを許可
private 対象の要素が属しているスコープ内のアクセスのみを許可

では、実際に利用してアクセスレベルを確認する


class SomeClass {
    
//オーバーライドを許可する場合
   open var a = "a"

//オーバーライドを許可しない場合
    public var b = "b"

//同一モジュールならOK
    internal var c = "c"

//同じファイル内ならOK
    fileprivate var d = "d"

//定義したスコープ内ならOK
    private var e = "e"
    
}

var some = SomeClass()
some.a // "a"
some.b // "b"
some.c // "c"
some.d // "d"

//アクセス修飾子がprivateのためエラーになる
some.e // 'e' is inaccessible due to 'private' protection level

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?