dynamic lookup
런타임에 class, structure, enum, protocol의 멤버들에 이름으로 접근 가능하도록 할 수 있는 attribute. 쉽게 표현해서, '.'을 이용해 멤버에 접근할 수 있는 기능을 제공하는 것.
아래의 예시에서처럼 'DynamicStruct'라는 struct에 @dynamicMemberLookup를 붙여주면, 'subscript(dynamicMember:)' method를 작성해주어야 한다. 예시에서는 subscript의 parameter를 dictionary의 key로 이용해서 value를 획득하는 형식이다.
@dynamicMemberLookup
struct DynamicStruct {
let dictionary = ["someDynamicMember": 325,
"someOtherMember": 787]
subscript(dynamicMember member: String) -> Int {
return dictionary[member] ?? 1054
}
}
let s = DynamicStruct()
// Use dynamic member lookup.
let dynamic = s.someDynamicMember
이렇게 subscript를 작성해주면, 객체에 '.'을 이용해서 바로 dictionary의 key를 사용할 수 있게 되는 것임.
s.dictionary["someDynamicMember"]로 값에 접근 하는 것보다 조금 더 깔끔하게 코드를 작성할 수 있다.
'.'을 이용하는 방식은 사실 상 s[dynamicMember: "someDynamicMember"] 와 같이 subscript를 직접 호출하는 것의 다른 표현이라고 볼 수 있다.
---
참고자료
Documentation
docs.swift.org
https://swiftwithmajid.com/2023/05/23/dynamic-member-lookup-in-swift/
Dynamic member lookup in Swift
One of my favorite features of the Swift Language is the dynamic member lookup. We don’t use it very often, but it improves the API of the provided type significantly by improving the way we access the data of the particular type.
swiftwithmajid.com