접근 제한자(Access Level)

인생노잼시기·2021년 8월 2일
0

🦅 스위프트 문법

목록 보기
11/13

Access Levels

privatefileprivateinternalpublicopen
같은 클래스
같은 파일
같은 모듈, 프로젝트
모듈 외부
모듈 외부 & 수정 가능

여기서 모듈이란❓
코드 상단에서 반입 선언하여 사용하는 라이브러리 중에서
UIKit, MapKit, UserNotification 등 프레임워크 단위를 이야기합니다

private은 비공개API인 경우이고
public은 공개API인 경우이다


  • private: {}
  • fileprivate
    ViewController.swift
  • internal
    기본값
    파란색 아이콘 하나
  • public
    모듈 여러개
    AppModule과 PodModule 모두에서 사용할 수 있다

    Pod의 경우 다른 개발자들도 추가해서 사용해야하므로 public으로 되어있는 것을 확인할 수 있다
    subclass와 override 불허
  • open
    subclass와 override 허용

실습

global & local varible + access level
여기에서 global변수는
aPrivateProperty, aFilePrivateProperty, anInternalProperty

main.swift

import Foundation

let aClass = AClass()

aClass.methodA()
aClass.methodB()

print(aClass.anInternalProperty)    // Possible

AFile.swift


import Foundation

class AClass {
    
    //Global variables, also called class properties.
    
    //같은 클래스
    private var aPrivateProperty = "private property"
    
    //같은 파일
    fileprivate var aFilePrivateProperty = "fileprivate property"
    
    var anInternalProperty = "internal property"
    
    func methodA () {
        
        var aLocalVariable = "local variable"
        
        //Step 1. Try to print aLocalVariable Here - Possible
        print("\(aLocalVariable) printed from methodA in AClass")
        
        //Step 3. Try to print aPrivateProperty Here - Possible
        print("\(aPrivateProperty) printed from methodA in AClass")
        
        //Step 6. Try to print aFilePrivateProperty Here - Possible
        print("\(aFilePrivateProperty) printed from methodA in AClass")
        
        //Step 9. Try to print anInternalProperty Here - Possible
        print("\(anInternalProperty) printed from methodA in AClass")
    }
    
    func methodB () {
        
        //Step 2. Try to print aLocalVariable Here - Impossible
        //print("\(aLocalVariable) printed from methodB in AClass")
        
        //Step 4. Try to print aPrivateProperty Here - Possible
        print("\(aPrivateProperty) printed from methodB in AClass")
        
        print("\(aFilePrivateProperty) printed from methodB in AClass") // Possible
        
        print("\(anInternalProperty) printed from methodB in AClass") // Possible
    }
    
}

class AnotherClassInTheSameFile {
    
    init() {
        
        //Step 5. Try to print aPrivateProperty Here - Impossible
        //print(aClass.aPrivateProperty)
        
        //Step 7. Try to print aFilePrivateProperty Here - Possible
        print(aClass.aFilePrivateProperty)
    }
}

AnotherFile.swift

import Foundation

class AnotherClassInAnotherFile {
    
    init() {
        
        //Step 8. Try to print aFilePrivateProperty Here - Impossible
        //print(aClass.aFilePrivateProperty)
        
        //Step 10. Try to print anInternalProperty Here - Possible
        print(aClass.anInternalProperty)
    }
    
}
profile
인생노잼

0개의 댓글