-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathuseful-global-swift-functions.html
More file actions
406 lines (353 loc) · 22.3 KB
/
useful-global-swift-functions.html
File metadata and controls
406 lines (353 loc) · 22.3 KB
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
<!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="Global functions, or functions that can be accessed from anywhere without the scope of a specific type is an old concept that was popular in languages like C and Objective-C, but unrecommended in Swift as we would rather have things that are nicely typed and scoped ("swifty"). For historical reasons, the Swift Standard Library still has quite a few public global functions, and some of them are still useful to this day. Let's take a look at functions like zip() and dump().">
<meta name="title" content="Useful Global Swift Functions">
<meta name="url" content="https://swiftrocks.com/useful-global-swift-functions">
<meta name="image" content="https://swiftrocks.com/images/thumbs/thumb_dark.jpg">
<meta name="copyright" content="Bruno Rocha">
<meta name="robots" content="index,follow">
<meta property="og:title" content="Useful Global Swift Functions"/>
<meta property="og:image" content="https://swiftrocks.com/images/thumbs/thumb_dark.jpg"/>
<meta property="og:description" content="Global functions, or functions that can be accessed from anywhere without the scope of a specific type is an old concept that was popular in languages like C and Objective-C, but unrecommended in Swift as we would rather have things that are nicely typed and scoped ("swifty"). For historical reasons, the Swift Standard Library still has quite a few public global functions, and some of them are still useful to this day. Let's take a look at functions like zip() and dump()."/>
<meta property="og:type" content="website"/>
<meta property="og:url" content="https://swiftrocks.com/useful-global-swift-functions"/>
<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content="https://swiftrocks.com/images/thumbs/thumb_dark.jpg"/>
<meta name="twitter:image:alt" content="Page Thumbnail"/>
<meta name="twitter:title" content="Useful Global Swift Functions"/>
<meta name="twitter:description" content="Global functions, or functions that can be accessed from anywhere without the scope of a specific type is an old concept that was popular in languages like C and Objective-C, but unrecommended in Swift as we would rather have things that are nicely typed and scoped ("swifty"). For historical reasons, the Swift Standard Library still has quite a few public global functions, and some of them are still useful to this day. Let's take a look at functions like zip() and dump()."/>
<meta name="twitter:site" content="@rockbruno_"/>
<meta name="fediverse:creator" content="@rockbruno@hachyderm.io">
<!-- Favicon -->
<!-- 16x16 -->
<link rel="shortcut icon" href="images/favicon/favicon.ico" type="image/x-icon">
<link rel="apple-touch-icon" href="images/favicon/favicon_180.png" sizes="180x180">
<link rel="icon" href="images/favicon/favicon_32.png" sizes="32x32" type="image/png">
<link rel="icon" href="images/favicon/favicon_48.png" sizes="48x48" type="image/png">
<link rel="icon" href="images/favicon/favicon_96.png" sizes="96x96" type="image/png">
<link rel="icon" href="images/favicon/favicon_144.png" sizes="144x144" type="image/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/useful-global-swift-functions"/>
<!-- Bootstrap CSS Plugins -->
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<!-- Prism CSS Stylesheet -->
<link rel="stylesheet" type="text/css" href="css/prism5.css">
<!-- Main CSS Stylesheet -->
<link rel="stylesheet" type="text/css" href="css/style49.css">
<link rel="stylesheet" type="text/css" href="css/sponsor5.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/useful-global-swift-functions"
},
"image": [
"https://swiftrocks.com/images/thumbs/thumb_dark.jpg"
],
"datePublished": "2020-03-24T07:25:00+00:00",
"dateModified": "2020-04-12T14: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_dark.jpg"
}
},
"headline": "Useful Global Swift Functions",
"abstract": "Global functions, or functions that can be accessed from anywhere without the scope of a specific type is an old concept that was popular in languages like C and Objective-C, but unrecommended in Swift as we would rather have things that are nicely typed and scoped ('swifty'). For historical reasons, the Swift Standard Library still has quite a few public global functions, and some of them are still useful to this day. Let's take a look at functions like zip() and dump()."
}
</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 class="logo-link" href="https://swiftrocks.com">
<img id="logo" class="logo" alt="SwiftRocks" src="images/bg/logo2dark.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=Useful Global Swift Functions-->
<!--WRITEIT_POST_HTML_NAME=useful-global-swift-functions-->
<!--WRITEIT_POST_SITEMAP_DATE_LAST_MOD=2020-04-12T14:00:00+02:00-->
<!--WRITEIT_POST_SITEMAP_DATE=2020-03-24T07:25: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=Global functions, or functions that can be accessed from anywhere without the scope of a specific type is an old concept that was popular in languages like C and Objective-C, but unrecommended in Swift as we would rather have things that are nicely typed and scoped ("swifty"). For historical reasons, the Swift Standard Library still has quite a few public global functions, and some of them are still useful to this day. Let's take a look at functions like zip() and dump().-->
<title>Useful Global Swift Functions</title>
<div class="blog-post">
<div class="post-title-index">
<h1>Useful Global Swift Functions</h1>
</div>
<div class="post-info">
<div class="post-info-text">
Published on 24 Mar 2020
</div>
</div>
<p><b>Global functions</b>, or functions that can be accessed from anywhere without the scope of a specific type is an old concept that was popular in languages like C and Objective-C, but unrecommended in Swift as we would rather have things that are nicely typed and scoped ("swifty").</p>
<div class="sponsor-article-ad-auto hidden"></div>
<p>For historical reasons, the Swift Standard Library still has quite a few public global functions, and some of them are still useful to this day. Let's take a look at functions like <code>zip()</code> and <code>dump()</code>.</p>
<h2>zip()</h2>
<p>Perhaps the most known global function, the <code>zip</code> function allows you to take two or more arrays and merge them into a single <code>Sequence</code> of a tuple. This is extremely useful if you need to iterate two things at the same time, as without <code>zip</code> you would have to manually build a <b>for</b> loop and access each index from each array individually. Using <code>zip</code> allows you access elements from all arrays in the more useful <b>for-in</b> fashion.</p>
<p>For example, if we had a user registration form screen and we would like to update our textFields to render a list of validation results fetched from the backend, we could do something like this:</p>
<pre><code>func present(validationResults: [FieldValidationResult],
inTextFields textFields: [MyTextField]) {
for i in 0..<textFields.count {
let field = textFields[i]
let result = validationResults[i]
field.render(validationResult: result)
}
}</code></pre>
<p>With <code>zip</code>, we can remove all the manual indexing.</p>
<pre><code>func present(validationResults: [FieldValidationResult],
inTextFields textFields: [MyTextField]) {
for (field, result) in zip(textFields, validationResults) {
field.render(validationResult: result)
}
}</code></pre>
<p>The return type of <code>zip</code> is a <code>Zip2Sequence</code> object that conforms to <code>Sequence</code>, and so all other sequence-related methods are applicable to it, including transforming it to a real array.</p>
<h2>dump()</h2>
<p>The <code>dump</code> function is a neat alternative to printing objects. While printing objects is just a syntax sugar for a type's <code>description</code> or <code>debugDescription</code> property, <code>dump</code> is a supercharged version of <code>Mirror(reflecting:)</code> that prints the contents of an object using reflection, which will usually result in considerably more info, including the hierarchy of the object.</p>
<pre><code>class Foo: NSObject {
let bar: String = "bar"
}
let foo = Foo()
print(foo)
// <SwiftRocks.Foo: 0x1030b9250>
dump(foo)
// ▿ <SwiftRocks.Foo: 0x1030b9250> #0
// - super: NSObject
// - bar: "bar"</code></pre>
<h2>sequence()</h2>
<p>The global <code>sequence()</code> function is a bit obscure, but it's a very cool function that lets you write recursive functions in a nicer syntax.</p>
<p>Let's pretend that we're changing the background color of a subview and all of its parents. Perhaps you would build a <code>while</code> loop like this:</p>
<pre><code>var currentView: UIView? = self
while currentView != nil {
currentView?.backgroundColor = .green
currentView = currentView?.superview
}</code></pre>
<p>This is the best use case for <code>sequence()</code>, as the purpose of this function is to give you a <code>Sequence</code> that applies a specific closure over and over. As the recursive aspect of this method (<code>currentView = currentView?.superview</code>) is always the same, we can use <code>sequence()</code> to turn it into a simple <code>for</code> loop:</p>
<pre><code>for view in sequence(first: self, next: { $0.superview } ) {
view.backgroundColor = .green
}</code></pre>
<p>The way this works is that <code>sequence()</code> returns a custom <code>UnfoldFirstSequence</code> type, a simple wrapper for a <code>Sequence</code> that keeps applying the closure over and over in its <code>next()</code> function.</p>
<h2>isKnownUniquelyReferenced()</h2>
<p>The <code>isKnownUniquelyReferenced</code> function receives a <code>class</code> object and returns a boolean that indicates if the object is being reference only one time, with the purpose of enabling you to implement <b>value semantics</b> to <b>reference types</b>. Although structs are value types themselves, the contents inside of it might not be. You might know that putting a class inside a struct doesn't mean it will be copied on assignment:</p>
<pre><code>class Foo: NSObject {
var bar: String = "bar"
}
struct FooHolder {
let foo: Foo = Foo()
var intValue: Int = 1
}
var fooHolder = FooHolder()
var fooHolder2 = fooHolder
fooHolder2.foo.bar = "bar2"
fooHolder2.intValue = 2
print(fooHolder.intValue)
// 1
print(fooHolder2.intValue)
// 2
print(fooHolder.foo.bar)
// bar2
print(fooHolder2.foo.bar)
// bar2</code></pre>
<p>In this example, although <code>fooHolder2</code> and its underlying number are separate entities from the original holder, the underlying class is still shared between them. To fix this, we can use <code>isKnownUniquelyReferenced</code> to detect when this property is being accessed and create a new instance of the class if necessary:</p>
<pre><code>struct FooHolder {
private var _foo: Foo = Foo()
var foo: Foo {
mutating get {
if isKnownUniquelyReferenced(&_foo) {
return _foo
} else {
let newFoo = Foo()
newFoo.bar = _foo.bar
_foo = newFoo
return _foo
}
} set {
_foo = newValue
}
}
var intValue: Int = 1
}</code></pre>
<p>You might be interested to know that this is exactly how the Swift Standard Library enables <b>copy-on-write</b> semantics to Arrays and Strings -- <a href="https://swiftrocks.com/memory-management-and-performance-of-value-types">something that I've mentioned in my article about the memory management of value types.</a></p>
<h2>repeatElement()</h2>
<p>The <code>repeatElement()</code> does exactly what it says. Given an object and a number, the result is a <code>Sequence</code> that can be iterated to give you that object that specific amount of times.</p>
<pre><code>let repeated: Repeated<String> = repeatElement("SwiftRocks", count: 3)
for value in repeated {
print(value)
}
//SwiftRocks
//SwiftRocks
//SwiftRocks</code></pre>
<p>Repeating elements is a common operation in Swift, especially to fill in gaps in <code>Strings</code> and <code>Arrays</code>. in fact, most of these types even have a specific initializer for this:</p>
<pre><code>let array = [Int](repeating: 0, count: 10)</code></pre>
<p><b>So why would you use repeatElement?</b> The reason is performance. The return type of <code>repeatElement()</code> is a <code>Repeated<T></code> <code>Sequence</code> type, similar to <code>Zip2Sequence</code> in terms that it does nothing besides provide this "repeating" functionality. Let's say you would like to replace a specific section of the array of numbers with another number; one way to achieve this would be to use <code>replaceSubrange</code> with another array:</p>
<pre><code>array.replaceSubrange(2...7, with: [Int](repeating: 1, count: 6))
print(array)
// [0, 0, 1, 1, 1, 1, 1, 1, 0, 0]</code></pre>
<p>While this works, the usage of <code>[Int](repeating:)</code> comes with all the overhead of having to initialize array buffers that will serve no purpose here. If you <b>only</b> need the repeating functionality, then using <code>repeatElement</code> will perform much better.</p>
<pre><code>array.replaceSubrange(2...7, with: repeatElement(1, count: 6))</code></pre>
<h2>stride()</h2>
<p>Also fairly popular, the <code>stride()</code> function was added to Swift as a way to create for loops that could skip certain elements, as the equivalent C-style way to do so was removed from the language:</p>
<pre><code>for (int i = 0; i < 10; i += 2) { ... }</code></pre>
<p>Now, you can use <code>stride()</code> to achieve the same behavior:</p>
<pre><code>for i in stride(from: 0, to: 10, by: 2) {
// from 0 to 9, skipping odd numbers.
}</code></pre>
<p>The arguments for <code>stride()</code> are arguments that conform to the <code>Strideable</code> protocol, which represents objects that can represent the concept of distances. For example, here's how we could add the concept of "day difference" in <code>Date</code> objects to that they can be used in <code>stride()</code>:</p>
<pre><code>extension Date: Strideable {
func advanced(by n: Int) -> Date {
return Calendar.current.date(byAdding: .day,
value: n,
to: self)!
}
func distance(to other: Date) -> Int {
return Calendar.current.dateComponents([.day],
from: other,
to: self).day!
}
}
let startDate = Date()
let finalDate = startDate.advanced(by: 5)
for date in stride(from: startDate, to: finalDate, by: 1) {
print(date)
}
// March 24th
// March 25th
// March 26th
// March 27th
// March 28th</code></pre>
<p><i>(Note that Date already has an implementation of Strideable methods that strides in seconds, so copying this to a project won't work.)</i></p>
<h2>Other Useful Functions</h2>
<h3>Math</h3>
<p><code>max()</code> - Returns the maximum value of the arguments</p>
<p><code>min()</code> - Returns the minimum value of the arguments</p>
<p><code>abs()</code> - Returns the absolute value of the argument (useful in competitive programming questions)</p>
<h3>Values</h3>
<div class="sponsor-article-ad-auto hidden"></div>
<p><code>swap()</code> - Swaps the value of two objects. This is not mentioned in its own section in this article because if you need to swap array elements the correct method to use is <code>Array.swapAt()</code>. However, you can still use <code>swap()</code> in other situations where you would need to create a fake "aux" property to hold a value.</p>
<h2>Conclusion</h2>
<p>As we can see, although none of these methods are necessary to make things happen, using them allows you write code that is easier to maintain and some times even more performant than old school solutions.</p>
</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://hachyderm.io/@rockbruno"><svg class="svg-logo-link" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M433 179.1c0-97.2-63.7-125.7-63.7-125.7-62.5-28.7-228.6-28.4-290.5 0 0 0-63.7 28.5-63.7 125.7 0 115.7-6.6 259.4 105.6 289.1 40.5 10.7 75.3 13 103.3 11.4 50.8-2.8 79.3-18.1 79.3-18.1l-1.7-36.9s-36.3 11.4-77.1 10.1c-40.4-1.4-83-4.4-89.6-54a102.5 102.5 0 0 1 -.9-13.9c85.6 20.9 158.7 9.1 178.8 6.7 56.1-6.7 105-41.3 111.2-72.9 9.8-49.8 9-121.5 9-121.5zm-75.1 125.2h-46.6v-114.2c0-49.7-64-51.6-64 6.9v62.5h-46.3V197c0-58.5-64-56.6-64-6.9v114.2H90.2c0-122.1-5.2-147.9 18.4-175 25.9-28.9 79.8-30.8 103.8 6.1l11.6 19.5 11.6-19.5c24.1-37.1 78.1-34.8 103.8-6.1 23.7 27.3 18.4 53 18.4 175z"/></svg></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/prism5.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>