Hamp 2025. 3. 19. 22:21
반응형

✊Mirror란

한번도 쓰지 않았지만 항상 프로젝트를 하면 팀원이 쓰던 녀석..

 

나도 한번 써보자..

 

공식문서를 살펴보자.

A representation of the substructure and display style of an instance of any type.

 

모든 타입의 인스턴스의 하위 구조display stlye를 나타내는 리플렉션 API라고 한다.

 

모든 타입이라고하는데 진짜 그런 지 살펴보자.

 

Mirror.DisplayStyle을 보면 swift의 거의 모든 타입을 커버하고 있다.

 


☝️주요 기능

주요 기능은 다음과 같다.

  • 프로퍼티와 값 탐색
  • 타입 확인
  • 디버깅 및 로깅
  • 타입 정보 추출

1️⃣ 프로퍼티와 값 탐색

chidren을 통해 인스턴스의 모든 프로퍼티와 값을 탐색할 수 있다.

struct Person {
    var name: String
    var age: Int
}

let person = Person(name: "hamp", age: 27)
let mirror = Mirror(reflecting: person)

for (label, value) in mirror.children {
    print("\(label!): \(value)")
}

/// OUTPUT
/// name: hamp
/// age: 27

2️⃣ 타입 확인

subjectType 프로퍼티를 통해 인스턴스의 타입 확인

struct Person {
    var name: String
    var age: Int

  func hello() {
    print("Hello")
  }
}

let person = Person(name: "hamp", age: 27)
let mirror = Mirror(reflecting: person)

print(mirror.subjectType)

/// OUTPUT
/// Person

 

3️⃣ 상위 타입 탐색

superclassMirror를 통해 상위 타입 탐색 확인

class Animal {}
class Dog: Animal {}

let dog = Dog()
let mirror = Mirror(reflecting: dog)

if let superClass = mirror.superclassMirror {
    print("Superclass: \(superClass.subjectType)")
}

/// OUTPUT
/// Animal

4️⃣ Enum Associated Value 추출

enum Result {
    case success(value: Int)
    case failure(error: String)
}

let result = Result.success(value: 42)
let mirror = Mirror(reflecting: result)

for child in mirror.children {
    print("Associated Value: \(child.value)")
}

/// OUTPUT
/// Associated Value: (value: 42)

😀 소감 및 마무리

Actor가 따로 안보이길래 해봤는데 신기한 결과가 나왔다.

class ClassA {
  var aa: Int = 10
}

var classA = ClassA()

let mirror = Mirror(reflecting: classA)
mirror.customMirror
print(mirror.displayStyle)
print(mirror.subjectType)
print(mirror.superclassMirror)
for child in mirror.children {
    print("property: \(child.value)")
}

/// OUTPUT
/// Optional(Swift.Mirror.DisplayStyle.class)
/// ClassA
/// nil
/// property: 10

 

 

먼저 class를 살펴보면 예상대로 잘 나온다.

actor AcotrA {
  var aa: Int = 10
}

var actor = AcotrA()

let mirror = Mirror(reflecting: actor)
mirror.customMirror
print(mirror.displayStyle)
print(mirror.subjectType)
print(mirror.superclassMirror)
for child in mirror.children {
    print("property: \(child)")
}

///Optional(Swift.Mirror.DisplayStyle.class)
///AcotrA
///nil
/// property: (label: Optional("$defaultActor"), value: (Opaque Value))
/// property: (label: Optional("aa"), value: 10)

 

Actor인데 ? displayStyle이 class로 분류된다.

 

그리고 chidren이 aa 프로퍼티 1개 밖에 없는데 $defaultActor라는 Opaque Value가 잡히고 있다.

 

아직 Actor에 대한 학습이 되지 않아 자세히는 모르겠다..

 

Actor 학습 후 정체가 무엇인지 알아내면 추가적으로 내용을 쓰겠다.


 

출처

https://developer.apple.com/documentation/swift/mirror

 

Mirror | Apple Developer Documentation

A representation of the substructure and display style of an instance of any type.

developer.apple.com

 

반응형