Swift Macro #unwrap

449 Views Asked by At

In Apple's WWDC 2023 they announced macros and, among others, they showed us this code snippet:

macro unwrap<Wrapped>(_ expr: Wrapped, message: String) -> Wrapped

I have downloaded Xcode 15 Beta and tried to get it to work, without result. I get the error message of:

Macro 'unwrap(_:message:)' requires a definition

What can I do or how can I write this correctly?

2

There are 2 best solutions below

1
li fang amibo On BEST ANSWER

You should create a new macro.In Xcode File → New → Package... and select Swift Macro

0
Iskandir On

I haven't found your code snippet, but instead take a look at the video of WWDC, Write Swift macros, 06:36.

When creating a macro you need to declare the definition of your macro... For example in the video...

We have the macro

let (result, code) = #stringify(a+b)

To dive into the definition of #stringify...

// A macro that produces both a value and a string containing
// the source code that generated the value

@freestanding(expression)
public macro stringify<T>(_ value: T) -> (T, String) = #externalMacro(module: "WWDCMacros", type: "StringifyMacro")

So I guess that you are just missing the correct implementation. Do you have a implementation file of your macro?

Does it have the correct initializer?

// Check the overview here:
@freestanding(expression) // Creates a piece of code that returns a value
@freestanding(declaration) // Creates one or more declarations
@attached(peer) // Adds new declarations alongside the declaration its applied to
@attached(accessor) // Adds accessors to a property
@attached(memberAttribute) // Adds new declarations inside the type/extension its applied to
@attached(member) // Adds new declarations inside the type/extension its applied to
@attached(conformance) // Adds conformances to the type/extension its applied to