Skip to content

Commit

Permalink
Add post about two types of Swift macros
Browse files Browse the repository at this point in the history
  • Loading branch information
Zaprogramiacz committed Nov 28, 2024
1 parent fd7fcc1 commit 8b576ca
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
46 changes: 46 additions & 0 deletions content/posts/two-types-of-swift-macros/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
---
title: 'Two types of Swift macros'
date: 2024-11-26
tags: ['Swift', 'Macro']
cover:
image: 'images/cover.png'
alt: 'Two types of Swift macros'
---

Explain `#` and `@` in Swift - your next interview may have this question! Don't miss it out!

Shortly - `#` and `@` are prefixes for macros in Swift.

What is macro?
💡 Macro is a feature that generates code during compilation. Unlike macros in C, which work like “find and replace”, Swift macros are type-safe and context aware, making them powerful tools reducing boilerplate code.

Two types of macros
1️⃣ attached - use `@` prefix, tied to a declaration adding extra logic to it, like: `@Test`, `@Model`, `@Observable`
2️⃣ freestanding - use `#` prefix, standalone code like `#expect`, `#Predicate`, `#warning`

Example of attached macro ⤵️
```swift
@Test func addition() { // tied to the declaration
...
}
```

Example of freestanding macro ⤵️
```swift
@Test func addition() {
#require(1 + 2 == 3) // not attached to a declaration
}
```

Bonus:
It’s possible to expand macros (especially the ones defined by you) and check what’s the implementation inside. ⤵️

![Expanded_macro](images/expand_macro.gif)

---

Thanks for reading. 📖

I hope you found it useful!

If you enjoy the topic don't forget to follow me on one of my social media - [LinkedIn](https://www.linkedin.com/in/maciej-gomolka/), [X](https://twitter.com/gomolka_maciej) or via [RSS](https://www.mobiledevdiary.com/index.xml) feed to keep up to speed. 🚀

0 comments on commit 8b576ca

Please sign in to comment.