Question about using @dynamicMemberLookup with enum KeyPath

Hi, I have an idea for adding @dynamicMemberLookup to an OptionSet and using an enum as it's dynamicMember, such as:

struct TestOption: OptionSet {
	let rawValue: UInt
	enum Options: UInt {
		case option1
		case option2
		case option3
		static let option4 = Options.option1 // add this for testing
	static subscript(dynamicMember keyPath: KeyPath<Options.Type, Options>) -> TestOption {
		let option = Options.self[keyPath: keyPath]
		return TestOption(rawValue: 1 << option.rawValue)

But it doesn't work at all, Xcode alerts me of these error:
TestOption.option1 // Dynamic key path member lookup cannot refer to enum case 'option1'
TestOption.option4 // Dynamic key path member lookup cannot refer to static member 'option4'

Is dynamicMemberLookup not supported in this way or was I just writing something wrong?


enum cases are static members, and static members cannot be referenced in keypaths, so what you want is not possible.

You'll have to use a string instead of a key path in the dynamicMember subscript.

Terms of Service

Privacy Policy

Cookie Policy