Mirror

2025. 3. 19. 22:21·Programing Langauge/swift
반응형

✊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

 

반응형

'Programing Langauge > swift' 카테고리의 다른 글

가독성 좋게 정규식 설계하기  (1) 2025.07.22
매크로  (0) 2025.06.28
@inlinable  (0) 2025.03.18
@frozen  (0) 2025.03.18
lazy  (1) 2025.02.04
'Programing Langauge/swift' 카테고리의 다른 글
  • 가독성 좋게 정규식 설계하기
  • 매크로
  • @inlinable
  • @frozen
Hamp
Hamp
남들에게 보여주기 부끄러운 잡다한 글을 적어 나가는 자칭 기술 블로그입니다.
  • Hamp
    Hamp의 분리수거함
    Hamp
  • 전체
    오늘
    어제
    • 분류 전체보기 (297)
      • CS (29)
        • 객체지향 (2)
        • Network (7)
        • OS (6)
        • 자료구조 (1)
        • LiveStreaming (3)
        • 이미지 (1)
        • 잡다한 질문 정리 (0)
        • Hardware (2)
        • 이론 (5)
        • 컴퓨터 그래픽스 (0)
      • Firebase (3)
      • Programing Langauge (36)
        • swift (31)
        • python (4)
        • Kotlin (1)
      • iOS (131)
        • UIKit (37)
        • Combine (1)
        • SwiftUI (32)
        • Framework (7)
        • Swift Concurrency (22)
        • Tuist (6)
        • Setting (10)
        • Modularization (1)
        • Instruments (6)
      • PS (59)
        • 프로그래머스 (24)
        • 백준 (13)
        • LeetCode (19)
        • 알고리즘 (3)
      • Git (18)
        • 명령어 (4)
        • 이론 (2)
        • hooks (1)
        • config (2)
        • action (7)
      • Shell Script (2)
      • Linux (6)
        • 명령어 (5)
      • Spring (9)
      • CI-CD (4)
      • Android (0)
        • Jetpack Compose (0)
  • 블로그 메뉴

    • 홈
    • 태그
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    lifecycle
    투포인터
    property
    dispatch
    프로그래머스
    UIKit
    백준
    concurrency
    CS
    AVFoundation
    dfs
    boostcamp
    Network
    SwiftUI
    IOS
    Swift
    GIT
    Tuist
    protocol
    dp
  • 최근 댓글

  • 최근 글

  • 반응형
  • hELLO· Designed By정상우.v4.10.0
Hamp
Mirror
상단으로

티스토리툴바