-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathinside-swiftui-compiler-magic.html
415 lines (366 loc) · 22.8 KB
/
inside-swiftui-compiler-magic.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://use.fontawesome.com/afd448ce82.js"></script>
<!-- Meta Tag -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- SEO -->
<meta name="author" content="Bruno Rocha">
<meta name="keywords" content="Software, Engineering, Blog, Posts, iOS, Xcode, Swift, Articles, Tutorials, OBJ-C, Objective-C, Apple">
<meta name="description" content="SwiftUI is a revolutionary framework announced by Apple in WWDC 2019 and you might've noticed that it looks pretty different from regular Swift. Let's see why.">
<meta name="title" content="Inside SwiftUI's Declarative Syntax's Compiler Magic">
<meta name="url" content="https://swiftrocks.com/inside-swiftui-compiler-magic">
<meta name="image" content="https://swiftrocks.com/images/thumbs/thumb.jpg?4">
<meta name="copyright" content="Bruno Rocha">
<meta name="robots" content="index,follow">
<meta property="og:title" content="Inside SwiftUI's Declarative Syntax's Compiler Magic"/>
<meta property="og:image" content="https://swiftrocks.com/images/thumbs/thumb.jpg?4"/>
<meta property="og:description" content="SwiftUI is a revolutionary framework announced by Apple in WWDC 2019 and you might've noticed that it looks pretty different from regular Swift. Let's see why."/>
<meta property="og:type" content="website"/>
<meta property="og:url" content="https://swiftrocks.com/inside-swiftui-compiler-magic"/>
<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content="https://swiftrocks.com/images/thumbs/thumb.jpg?4"/>
<meta name="twitter:image:alt" content="Page Thumbnail"/>
<meta name="twitter:title" content="Inside SwiftUI's Declarative Syntax's Compiler Magic"/>
<meta name="twitter:description" content="SwiftUI is a revolutionary framework announced by Apple in WWDC 2019 and you might've noticed that it looks pretty different from regular Swift. Let's see why."/>
<meta name="twitter:site" content="@rockbruno_"/>
<!-- Favicon -->
<link rel="icon" type="image/png" href="images/favicon/iconsmall2.png" sizes="32x32" />
<link rel="apple-touch-icon" href="images/favicon/iconsmall2.png">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Source+Sans+3:ital,wght@0,200..900;1,200..900&display=swap" rel="stylesheet">
<link rel="canonical" href="https://swiftrocks.com/inside-swiftui-compiler-magic"/>
<!-- Bootstrap CSS Plugins -->
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<!-- Prism CSS Stylesheet -->
<link rel="stylesheet" type="text/css" href="css/prism4.css">
<!-- Main CSS Stylesheet -->
<link rel="stylesheet" type="text/css" href="css/style48.css">
<link rel="stylesheet" type="text/css" href="css/sponsor4.css">
<!-- HTML5 shiv and Respond.js support IE8 or Older for HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "BlogPosting",
"mainEntityOfPage": {
"@type": "WebPage",
"@id": "https://swiftrocks.com/inside-swiftui-compiler-magic"
},
"image": [
"https://swiftrocks.com/images/thumbs/thumb.jpg"
],
"datePublished": "2019-06-04T18:00:00+00:00",
"dateModified": "2022-10-11T14:00:00+02:00",
"author": {
"@type": "Person",
"name": "Bruno Rocha"
},
"publisher": {
"@type": "Organization",
"name": "SwiftRocks",
"logo": {
"@type": "ImageObject",
"url": "https://swiftrocks.com/images/thumbs/thumb.jpg"
}
},
"headline": "Inside SwiftUI's Declarative Syntax's Compiler Magic",
"abstract": "SwiftUI is a revolutionary framework announced by Apple in WWDC 2019 and you might've noticed that it looks pretty different from regular Swift. Let's see why."
}
</script>
</head>
<body>
<div id="main">
<!-- Blog Header -->
<!-- Blog Post (Right Sidebar) Start -->
<div class="container">
<div class="col-xs-12">
<div class="page-body">
<div class="row">
<div><a href="https://swiftrocks.com">
<img id="logo" class="logo" alt="SwiftRocks" src="images/bg/logo2light.png">
</a>
<div class="menu-large">
<div class="menu-arrow-right"></div>
<div class="menu-header menu-header-large">
<div class="menu-item">
<a href="blog">blog</a>
</div>
<div class="menu-item">
<a href="about">about</a>
</div>
<div class="menu-item">
<a href="talks">talks</a>
</div>
<div class="menu-item">
<a href="projects">projects</a>
</div>
<div class="menu-item">
<a href="software-engineering-book-recommendations">book recs</a>
</div>
<div class="menu-item">
<a href="games">game recs</a>
</div>
<div class="menu-arrow-right-2"></div>
</div>
</div>
<div class="menu-small">
<div class="menu-arrow-right"></div>
<div class="menu-header menu-header-small-1">
<div class="menu-item">
<a href="blog">blog</a>
</div>
<div class="menu-item">
<a href="about">about</a>
</div>
<div class="menu-item">
<a href="talks">talks</a>
</div>
<div class="menu-item">
<a href="projects">projects</a>
</div>
<div class="menu-arrow-right-2"></div>
</div>
<div class="menu-arrow-right"></div>
<div class="menu-header menu-header-small-2">
<div class="menu-item">
<a href="software-engineering-book-recommendations">book recs</a>
</div>
<div class="menu-item">
<a href="games">game recs</a>
</div>
<div class="menu-arrow-right-2"></div>
</div>
</div>
</div>
<div class="content-page" id="WRITEIT_DYNAMIC_CONTENT">
<!--WRITEIT_POST_NAME=Inside SwiftUI's Declarative Syntax's Compiler Magic-->
<!--WRITEIT_POST_HTML_NAME=inside-swiftui-compiler-magic-->
<!--WRITEIT_POST_SITEMAP_DATE_LAST_MOD=2022-10-11T14:00:00+02:00-->
<!--WRITEIT_POST_SITEMAP_DATE=2019-06-04T18:00:00+00:00-->
<!--Add here the additional properties that you want each page to possess.-->
<!--These properties can be used to change content in the template page or in the page itself as shown here.-->
<!--Properties must start with 'WRITEIT_POST'.-->
<!--Writeit provides and injects WRITEIT_POST_NAME and WRITEIT_POST_HTML_NAME by default.-->
<!--WRITEIT_POST_SHORT_DESCRIPTION=SwiftUI is a revolutionary framework announced by Apple in WWDC 2019 and you might've noticed that it looks pretty different from regular Swift. Let's see why.-->
<title>Inside SwiftUI's Declarative Syntax's Compiler Magic</title>
<div class="blog-post">
<div class="post-title-index">
<h1>Inside SwiftUI's Declarative Syntax's Compiler Magic</h1>
</div>
<div class="post-info">
<div class="post-info-text">
Published on 04 Jun 2019
</div>
</div>
<p>Announced in WWDC 2019, SwiftUI is an incredible UI building framework that might forever change how iOS apps are made. For years we've engaged in the war of writing views via Storyboard or View Code, and SwiftUI seems to finally end this. With its release, not only Storyboards are now pretty much irrelevant, but the old fashioned View Code is also very threatened as SwiftUI mixes the best of both worlds.</p>
<div class="sponsor-article-ad-auto hidden"></div>
<p>With this new framework, you can use Xcode to define your screens visually just like in Storyboards -- but instead of generating unreadable XML files, it generates code:</p>
<div class="post-image margin-top-40 margin-bottom-40">
<img src="https://i.imgur.com/NfE8605.png" alt="">
</div>
<p>If that wasn't crazy enough, changes to the code will update a live preview in real time, bringing to Xcode a long requested feature.</p>
<p>But the part that interests me most is that if you take a look at the SwiftUI examples, you'll see that almost appear to make no sense at all in current Swift -- how the hell can a bunch of seemingly disconnected <code>View</code> properties result in a complete screen?</p>
<pre><code>struct LandmarkList: View {
@State var showFavoritesOnly = true
var body: some View {
NavigationView {
List {
Toggle(isOn: $showFavoritesOnly) {
Text("Favorites only")
}
ForEach(landmarkData) { landmark in
if !self.showFavoritesOnly || landmark.isFavorite {
NavigationButton(destination: LandmarkDetail(landmark: landmark)) {
LandmarkRow(landmark: landmark)
}
}
}
}
.navigationBarTitle(Text("Landmarks"))
)
}
}</code></pre>
<p>Having strong support for declarative programming paradigms (where you describe what you want instead of explicitly coding it) was always a goal of Swift, and the release of SwiftUI is finally applying this concept. However, Swift doesn't have these features <i>yet</i>; The reason the previous example works is that SwiftUI is powered by tons of compiler features -- some of them coming in Swift 5.1, and others that still aren't officially part of Swift. As always, I investigated that out.</p>
<h2>Return-less single expressions</h2>
<p>You might have noticed that although <code>body</code> returns a <code>View</code>, there's no <code>return</code> statement! Swift 5.1 introduces return-less single expressions, where closures consisting of only one expression are allowed to omit the <code>return</code> statement for visual purposes. The way it works is what you'd expect: when the compiler is parsing a function body and notices it only has a single statement, it injects a <code>return</code> token in the tree. <a href="https://github.com/apple/swift/blob/0dc0b035218ca4412cbebd2a4d61a019b6b71ea0/lib/Parse/ParseDecl.cpp#L5683">Check it out here.</a></p>
<pre><code>auto RS = new (Context) ReturnStmt(SourceLoc(), E);
BS->setElement(0, RS);
AFD->setHasSingleExpressionBody();
AFD->setSingleExpressionBody(E);</code></pre>
<p>Although I personally think that this can be a little confusing (but I haven't used it much, so I might change my mind), this is really great to bring the declarative feeling into the language.</p>
<h2>Property Wrappers</h2>
<p>One of the most interesting features of SwiftUI is how changing the state of your view can trigger a full UI reload of it. This is enabled by the fact that Xcode 11 adds the <a href="https://developer.apple.com/documentation/combine">Combine</a> framework, officially bringing tons of Reactive concepts to iOS in the shape of declarative Swift APIs. However, what's cooler isn't these concepts themselves, but how they are applied. The previous example contains this line:</p>
<pre><code>@State var showFavoritesOnly = false</code></pre>
<p>Because this property is marked with the <code>@State</code> attribute, changing it triggers <code>body</code>, resulting in a new <code>View</code> being drawn in the screen.</p>
<p>This attribute isn't available in Swift itself, but it relates to a compiler feature that is currently under discussion to be added officially into the language: <b>property wrappers.</b></p>
<p>Sometimes, we want to add more complex pieces of logic to a property that doesn't really justify the use of a new type, at least not that in that scope. This can with the <code>get/set/willSet/didSet</code> property observers, like in the classic <code>UserDefaults</code> example:</p>
<pre><code>var isFirstBoot: Bool {
get {
return UserDefaults.standard.object(forKey: key) as? Bool ?? false
} set {
UserDefaults.standard.set(newValue, forKey: "isFirstBoot")
}
}</code></pre>
<p>This example is simple enough to work, but it's not difficult to see how bloated this gets if you do something more complex, like manually implementing the <code>lazy</code> logic:</p>
<pre><code>private var _foo: Int?
var lazyFoo: Int {
get {
if let value = _foo { return value }
let initialValue = 1738
_foo = initialValue
return initialValue
} set {
_foo = newValue
}
}</code></pre>
<p>In current Swift your only choice would be to wrap this inside a <code>Lazy<T></code> generic type, which visually doesn't fit SwiftUI's declarative programming style. In response, the <a href="https://github.com/apple/swift-evolution/blob/master/proposals/0258-property-delegates.md">Property Wrappers</a> proposal was created in April 2019. This compiler feature isn't officially added to the language yet, but it's already being used as part of SwiftUI. Its purpose is to do exactly what we have to do in current Swift, but visually <b>abstracting it from the user</b>.</p>
<p>When creating generic types, you can now add the <code>@propertyWrapper</code> attribute to its declaration to make it <b>usable as an attribute:</b></p>
<pre><code>@propertyWrapper struct UserDefault<T> {
let key: String
let defaultValue: T
var value: T {
get {
return UserDefaults.standard.object(forKey: key) as? T ?? defaultValue
} set {
UserDefaults.standard.set(newValue, forKey: key)
}
}
}</code></pre>
<p>I can now use <code>isFirstBoot</code> as follows:</p>
<pre><code>@UserDefault(key: "isFirstBoot", defaultValue: false) var isFirstBoot: Bool</code></pre>
<p>This allows you to interface with the complex generic type, but visually see nothing but a regular <code>Bool</code> property, As stated, the attribute empowers compiler magic to abstract the creation of the original generic type. Because the full implementation of it deserves an <code>How 'x' Works Internally in Swift</code> article of its own, we'll jump to the interesting parts -- with property wrappers, the compiler translates the previous declaration to this:</p>
<pre><code>var $isFirstBoot: UserDefaults<Bool> = UserDefaults<Bool>(key: "isFirstBoot", defaultValue: false)
var isFirstBoot: Bool {
get { return $isFirstBoot.value }
set { $isFirstBoot.value = newValue }
}</code></pre>
<p>The use of <code>$</code> as a prefix is on purpose; Even though <code>isFirstBoot</code> is a <code>Bool</code>, I might still want to access properties and methods from the more complex generic type. Although the original property is hidden, you can still access it for this purpose. For example, here's an example where <code>UserDefault</code> has a method for returning it to the default value:</p>
<pre><code>extension UserDefault {
func reset() {
value = defaultValue
}
}</code></pre>
<p>Although <code>Bool</code> won't have this property, I can use it from <code>$isFirstBoot</code>:</p>
<pre><code>$isFirstBoot.reset()</code></pre>
<p>This is why <code>Toggle(isOn: $showFavoritesOnly)</code> in SwiftUI's example use <code>$</code>: it doesn't want the actual <code>Bool</code>, but the <code>Binding</code> property provided by the <code>State</code> property wrapper struct which will be able to trigger a view reload when it changes.</p>
<pre><code>/// A linked View property that instantiates a persistent state
/// value of type `Value`, allowing the view to read and update its
/// value.
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
@propertyWrapper public struct State<Value> : DynamicViewProperty, BindingConvertible {
/// Initialize with the provided initial value.
public init(initialValue value: Value)
/// The current state value.
public var value: Value { get nonmutating set }
/// Returns a binding referencing the state value.
public var binding: Binding<Value> { get }
/// Produces the binding referencing this state value
public var delegateValue: Binding<Value> { get }
/// Produces the binding referencing this state value
/// TODO: old name for storageValue, to be removed
public var storageValue: Binding<Value> { get }
}</code></pre>
<h2>Result Builders</h2>
<p>We've seen how single expression don't need to add <code>return</code> statements, but what the hell is going on here?</p>
<pre><code>HStack {
Text("Hi")
Text("Swift")
Text("Rocks")
}</code></pre>
<p>This will result in a nice horizontal stack with three labels, but all we did was instantiate them! How could they be added to the view?</p>
<p>The answer to this is perhaps the most groundbreaking change in SwiftUI -- <b>result builders.</b></p>
<p>The resulkt builders feature pitch was introduced to the Swift community right after SwiftUI was released, allowing Swift to abstract factory patterns into a clean visual declarative expression. All indicates that it'll be part of Swift itself very soon, but for now you can try it as part of SwiftUI.</p>
<p>Result builders relate to types that, given a closure, can retrieve a sequence of statements and abstract the creation of something more concrete based on them.</p>
<p><code>HStack</code> can do this because it has the <code>ViewBuilder</code> result builder in its signature:</p>
<pre><code>public init(..., content: @ViewBuilder () -> Content)
//Note: The official docs won't show the attribute, and I'm not sure why,
//but you can confirm it has it by adding a normal expression `let a = 1` expression inside of the closure.
//It will give you a compilation error.</code></pre>
<p><code>@ViewBuilder</code> translates to the <code>ViewBuilder</code> struct: a <b>result builder</b> that can transform view expressions into actual views. Result builders are determined by the <code>@resultBuilder</code> attribute (with an underline because we're not supposed to use it manually yet) and a series of methods that determine how expressions should be parsed:</p>
<pre><code>@resultBuilder public struct ViewBuilder {
/// Builds an empty view from an block containing no statements, `{ }`.
public static func buildBlock() -> EmptyView
/// Passes a single view written as a child view (e..g, `{ Text("Hello") }`) through
/// unmodified.
public static func buildBlock
<content>
(_ content: Content) -> Content where Content : View
</content>
// Not here: Another 9 buildBlock methods with increasing amount of generic parameters
}</code></pre>
<p>We don't really know what's going on inside these methods as they are internal to SwiftUI, but we know the compiler magic behind it. That example will result in the following:</p>
<pre><code>HStack {
return ViewBuilder.buildBlock(Text("Hi"), Text("Swift"), Text("Rocks"))
}</code></pre>
<p>The more complex the block, the more complex the magic'd expression is. The important thing here is that result builders block can <b>only contain content that is understandable by the builder.</b> For example, you can only add an <code>if</code> statement to <code>HStack</code> because it contains the related <code>buildIf()</code> method from the attribute. If you want an example of something that doesn't work, try the following:</p>
<pre><code>HStack {
let a = 1 //Closure containing a declaration cannot be used with result builder 'ViewBuilder'
Text("a")
}</code></pre>
<p>The purpose of this feature is to enable the creation of embedded DSLs in Swift -- allowing you to define content that gets translated to something else down the line, but it plays a big role in giving the declarative programming feeling to Swift. Here's how building a HTML page can look with this result builders:</p>
<pre><code>div {
p {
"Call me Ishmael. Some years ago"
}
p {
"There is now your insular city"
}
}</code></pre>
<p>The version of the feature inside Xcode 11 is internal and has less features than the proposed Swift version, and thus shouldn't be used manually until it's officially added into the language.</p>
<h2>Conclusion</h2>
<div class="sponsor-article-ad-auto hidden"></div>
<p>SwiftUI has just been announced and it's already causing a huge impact. The new Swift features that are spawning out it are also game changing, and I for one am ready for the addition of new compiler black magics into Swift.</p>
<p>Follow me on my Twitter (<a href="https://twitter.com/rockbruno_">@rockbruno_</a>), and let me know of any suggestions and corrections you want to share.</p>
<h2>References and Good reads</h2>
<a href="https://github.com/apple/swift-evolution/blob/master/proposals/0258-property-delegates.md">SE-0258: Property Wrappers</a>
<br>
<a href="https://github.com/apple/swift/pull/23251">Original Returnless Expressions PR</a>
<br>
<a href="https://forums.swift.org/t/pitch-function-builders/25167">Result Builders Pitch</a>
<br>
</div></div>
<div class="blog-post footer-main">
<div class="footer-logos">
<a href="https://swiftrocks.com/rss.xml"><i class="fa fa-rss"></i></a>
<a href="https://twitter.com/rockbruno_"><i class="fa fa-twitter"></i></a>
<a href="https://github.com/rockbruno"><i class="fa fa-github"></i></a>
</div>
<div class="footer-text">
© 2025 Bruno Rocha
</div>
<div class="footer-text">
<p><a href="https://swiftrocks.com">Home</a> / <a href="blog">See all posts</a></p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Blog Post (Right Sidebar) End -->
</div>
</div>
</div>
<!-- All Javascript Plugins -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script type="text/javascript" src="js/prism4.js"></script>
<!-- Main Javascript File -->
<script type="text/javascript" src="js/scripts30.js"></script>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-H8KZTWSQ1R"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-H8KZTWSQ1R');
</script>
</body>
</html>