Notice
Recent Posts
Recent Comments
Link
관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift] Swift Macro의 종류 (Freestanding, Attached) 본문

Swift Macro

[iOS - swift] Swift Macro의 종류 (Freestanding, Attached)

jake-kim 2023. 9. 6. 01:44

Swift Macro는 2가지 타입

  • 독립형(Freestanding) 매크로: #(샾) 키워드로 시작, 다른 코드에 영향을 주지 않는 코드

ex) #function은 독립형 매크로

final class MyView: UIView {
    init() {
        super.init(frame: .zero)
    }
    
    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("\(#function) not implemented")
    }
}
  • 첨부형(Attached) 매크로: @(엣) 키워드로 시작, 다른 코드에 영향을 주는 코드

ex) struct 위에 wrapStoredProperties라는 매크로를 붙여서 x property에 영향을 주는 것

// https://github.com/DougGregor/swift-macro-examples/blob/main/MacroExamples/main.swift

@wrapStoredProperties(#"available(*, deprecated, message: "hands off my data")"#)
struct OldStorage {
  var x: Int
}
  • Swift Macro는 2가지 타입이며 이 2가지 타입은 각각 여러가지 role이 존재 (아래에서 계속)

Freestanding 매크로 role

  • freestanding(expression): 미리 정의한 값 반환

#function

@available(*, unavailable)
required init?(coder: NSCoder) {
    fatalError("\(#function) not implemented") // <-
}
  • freestanding(declaration): 특정 인수를 받아서 처리

#warning

#warning("Something's wrong")

Attached 매크로 role

  • attached(peer): 적용되는 선언과 함께 새 선언을 추가
@attached(peer, names: overloaded)
macro AddCompletionHandler(parameterName: String = "completionHandler")
  • attached(accessor): property에 get, set, willSet, didSet과 같은 접근자를 추가하는 매크로

https://ios-development.tistory.com/1405

  • attached(memberAttribute): property wrapper처럼 사용하며, 각 property에 일괄 적용하여 생략 가능하게 사용 가능한 방법

@attached(memberAttribute) 프로퍼티 위에 매번 선언하는 DictionaryRepresentable 생략 가능

  • attached(member): 기존에는 기존의 멤버에 새로운 특성을 추가했지만, @attached(member)는 완전히 새로운 멤버를 추가
    • * 멤버: method, property, initializer

  • attached(conformance): 적용되는 유형/확장에 적합성을 자동으로 추가

ex) @attached(conformance)를 추가하여 Person 구조체에 일일이 DictionaryRepresentable을 준수하도록 해주지 않아도 됨 

DictionaryRepresentable을 선언해주지 않아도 됨 (@attached(conformance)에 의해서 자동으로 암시적으로 추가)

이어서, 본격적으로 Macro 개발 시작하기는 다음 포스팅 글 참고

 

* 참고

https://ios-development.tistory.com/1405

https://docs.swift.org/swift-book/documentation/the-swift-programming-language/macros/

https://github.com/DougGregor/swift-macro-examples/blob/main/MacroExamples/main.swift

https://betterprogramming.pub/use-swift-macros-to-initialize-a-structure-516728c5fb49

Comments