Swift : namespace

Wooyo·2023년 9월 1일
0
post-thumbnail

참고 블로그 : https://bicycleforthemind.tistory.com/26

Namespace 란?

  • 연관된 값들을 한 공간에 이름을 지어 모아둔 공간
  • 라벨링과 비슷하며 유지보수 및 재사용성이 좋아진다.

무엇으로 Namespace를 구현할 것인가?

열거형 (enum)을 사용

  • 열거 형에 연산 프로퍼티를 사용
enum helloWorld {
	case hello
   	case world
    
    var message: String {
    	switch self {
        	case .hello:
            	return "hello"
            case .world:
            	return "world"
        }
    }
}

print(helloWorld.hello.message) // "hello"
  • case없는 열거형을 이용
enum helloWorld {
	static let hello = "hello"
    static let world = "world"
}

print(helloWorld.hello) // "hello"

구조체(stuct)을 사용

  • 일반적 구조체로 구현 (인스턴스 생성필요)
struct helloWorld {
	static let hello = "hello"
    static let world = "world"
}

let hello = helloWorld()

print(hello.hello) // "hello"
  • 불필요한 인스턴스 생성제거
struct helloWorld {
	static let hello = "hello"
    static let world = "world"
    
    private init() {}
}

let hello = helloWorld()
// 'helloWorld' initializer is inaccessible due to 'private' protection level
profile
Wooyo의 개발 블로그

0개의 댓글