LoginSignup
0
0

More than 5 years have passed since last update.

アクセス修飾子についての備忘録

Last updated at Posted at 2018-12-04

今回、初めてプロジェクトにアクセス修飾子を使いました!
以前まで、規制するために使うものなんだなと感じていた程度だったので
調べてわかったことを改めて記事に残そうと思います!

private

・private:クラス内からのみアクセス可能になる

class Aisatsu {
  private var morning = "おはよう"
  private var hello = "こんにちは"
  func morningGreeting() {
    print(morning)
  }
  private func helloGreeting() {
  print(hello)
  }
}
let aisatsu = Aisatsu()
print(aisatsu.morningGreeting()) //おはよう
print(aisatsu.helloGreeting()) // error

Swift4からextensionでもprivateプロパティにアクセス可能になりました。
https://dev.classmethod.jp/smartphone/iphone/swift4-private-and-fileprivate/

fileprivate

fileprivate: 同一ファイル内のみアクセス可能

class Aisatsu {
  private var morning = "おはよう"
  private var hello = "こんにちは"
  func morningGreeting() {
    print(morning)
  }
  fileprivate func helloGreeting() {
  print(hello)
  }
}
let aisatsu = Aisatsu()
print(aisatsu.morningGreeting()) //おはよう
print(aisatsu.helloGreeting()) // こんにちは

privateで書いていたメソッドをfileprivateでかくとprint文が表示されました。

public

モジュール外からでもアクセス可能

終わりに

修飾子を使い分けてコードをかけるようになりたいです。
今回他の方の記事や参考サイトを見ながら確認することが出来ました。
ありがとうございました。
http://swift.tecc0.com/?p=631
https://dev.classmethod.jp/smartphone/iphone/swift4-private-and-fileprivate/

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