iOS 응용 (swift)
[iOS - swift] private 프로퍼티 접근하는 방법 (#Mirror, private var, private let 프로퍼티 접근)
jake-kim
2023. 10. 8. 01:55
private 프로퍼티 접근 아이디어
- Mirror를 통해 property의 문자열 이름을 통해 접근
- Mirror란?
- 인스턴스의 *display style과 하위 정보를 표현하는 구조체
* display style: struct인지, class인지, enum인지 구분을 위한 값 - Mirror는 특정 인스턴스의 타입, 그 인스턴스의 하위 값(인스턴스, 메소드 등)의 정보를 가지고 있는 것
- 구체적인 개념은 이전 포스팅 글 참고
- 인스턴스의 *display style과 하위 정보를 표현하는 구조체

Mirror로 private 프로퍼티 접근하기
- 예제 코드 준비
- 외부에서 SomeClass의 private 프로퍼티인 name에 접근하는게 목적
- 아래처럼 private 키워드를 사용하면 사용하는쪽에서 접근이 불가능
import UIKit
class SomeClass {
private var name = "jake"
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let instance = SomeClass()
instance.name // 'name' is inaccessible due to 'private' protection level
}
}
- private 접근 방법
- Mirror로 instance를 감싼다음 "name"의 이름으로 접근하는것
- Mirror로 instance를 감싸기
let mirror = Mirror(reflecting: instance)
- mirror의 children, first(where:)를 사용한 후 값이 필요하므로 value로 접근하면 완료
let name = mirror
.children
.first { label, _ in label == "name" }?
.value
print(name) // "jake"
이름으로 private 프로퍼티 접근 추상화
- Mirror에 extension으로 확장
extension Mirror {
func property(name: String) -> Any? {
children
.first { label, _ in label == name }?
.value
}
}
- 쉽게 접근 가능
class SomeClass {
private var name = "jake"
private var age = 20
}
print(mirror.property(name: "name")) // "jake"
print(mirror.property(name: "age")) // 20
- 전역함수로 만들면 사용하는쪽에서 Mirror를 만들필요도 없이 간편하게 사용이 가능
func property(instance: Any, propertyName: String) -> Any? {
Mirror(reflecting: instance)
.property(name: propertyName)
}
print(property(instance: instance, propertyName: "name")) // "jake"
* 전체 코드: https://github.com/JK0369/ExAccessPrivateProperty
* 참고
https://developer.apple.com/documentation/swift/mirror
https://www.swiftwithvincent.com/newsletter/are-private-properties-really-private