Post

Modifier의 생김새 (메서드 체이닝)

Modifier의 생김새 (메서드 체이닝)

Modifier의 기본 구조

SwiftUI의 Modifier는 View에 스타일이나 동작을 연속해서 적용할 수 있도록 구성되어 있다. 내부적으로는 메서드 체이닝 구조이며, self를 반환하기 때문에 다음 Modifier를 계속 이어 붙일 수 있다.

1
2
3
4
Text("Hello")
    .font(.title)
    .foregroundColor(.red)
    .padding()

Modifier는 왜 체이닝이 가능한가?

  • .font(), .foregroundColor() 같은 메서드는 전부 some View를 반환한다.
  • 즉, 새로운 View를 반환하기 때문에 다음 메서드를 또 붙일 수 있다.

Modifier가 반환하는 구조 (실제 타입)

1
2
3
Text("Hello")
    .font(.title) // ModifiedContent<Text, _EnvironmentKeyWritingModifier<Font>>
    .foregroundColor(.red) // ModifiedContent<ModifiedContent<...>, _EnvironmentKeyWritingModifier<Color>>
  • 각 Modifier는 ModifiedContent<Content, Modifier> 형태의 새 View를 생성한다.

사용자 정의 Modifier 만들기

1
2
3
4
5
6
7
8
struct RoundedBlueBackground: ViewModifier {
    func body(content: Content) -> some View {
        content
            .padding()
            .background(Color.blue)
            .cornerRadius(10)
    }
}

View 확장으로 Modifier 적용

1
2
3
4
5
extension View {
    func roundedBlue() -> some View {
        self.modifier(RoundedBlueBackground())
    }
}

호출 예시

1
2
3
Text("Hello")
    .roundedBlue()
    .font(.headline)

메서드 체이닝을 Swift 문법으로 흉내내기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct CustomView {
    var text: String = "default"

    func setText(_ value: String) -> CustomView {
        var copy = self
        copy.text = value
        return copy
    }

    func styled() -> CustomView {
        print("스타일 적용: \(text)")
        return self
    }
}

사용 예시

1
2
3
CustomView()
    .setText("Hello")
    .styled()

SwiftUI Modifier 체이닝과 유사한 조건

  1. 각 메서드는 self 또는 새로운 View를 반환해야 함
  2. 메서드 자체는 View 프로토콜을 따르는 타입에서 정의되어야 함
  3. 내부적으로 ModifiedContent<Content, Modifier>로 감싸서 새로 반환함

결론

SwiftUI의 Modifier는 메서드 체이닝을 가능하게 하기 위해 모든 Modifier가 새로운 View를 반환하도록 설계되어 있다. 이 구조 덕분에 깔끔하고 선언적인 UI 코드를 작성할 수 있으며, 필요할 경우 사용자 정의 Modifier도 동일한 방식으로 만들 수 있다.

핵심은 “모든 Modifier는 View를 반환하며, View는 또 다른 Modifier를 붙일 수 있다”는 점이다.

This post is licensed under CC BY 4.0 by the author.