Swift Collection's prefix for quick tests
This is a small trick that I use when I’m writing a script in Swift that performs some operation in a large number of objects, usually files. More often than not this operation is somehow destructive and ends up overwriting the original file, so I want to make sure that I got the changes right before applying it to the entire set of data.
Usually this means that I just want to stop a loop on its first iteration.
There are many ways of doing this, probably the most common one you can think of is using a break
if you’re using a for in
:
for file in files {
....
break
}
Another way is by just getting the first element of the array an applying the operation to it manually, but this means commenting some code, which is too invasive for my taste:
//for file in files {
let file = files[0]
....
//}
For me the best way is by using Swift Collection’s prefix operations, in this case by getting a prefix of 1.
for file in files.prefix(1) {
....
}
The advantage of this technique is that the change is located on the loop itself and that the body, the meat of the operation, is not affected by it. Is the less invasive technique that I’ve found and it allows me to quickly debug a change with a single file without affecting the entire set.
Another advantage of using prefix
as opposed to break
is that it works with forEach
, which I tend to use very often.
files.prefix(1).forEach { file in
...
}
That’s it! I quick tip for your Swift scripts ^^