-
Learning Swift - For-Loops
Loops are a fundamental building block of any program. Doing repetitive tasks fast and accurately is what computers are really good at and what we humans get very bored doing. Swift offers several different ways to perform loops, but today we are going to concentrate on for-loops.
The most basic form of loop is the
for-in
loop. There are two ways this can be used: looping over the numbers in a range or looping over the elements in an array or dictionary.Firstly, the range:
for x in 0 ..< 5 { printWithSpace(x) } // prints: 0 1 2 3 4
I am using a custom print function that allows me to print the results on a single line for convenience.
-
Learning Swift - Generics
One of the nice things about Swift is how clean your code looks. A lot of the weird characters that pepper the code of other languages has been eliminated: No more semi-colons, asterisks etc.
But then you are reading somebody else's code and you find these angle brackets all over the place and they don't seem to make sense.
What does this mean?
func mid<T: Comparable>(array: [T]) -> T
It looks like it is a function to find the middle element in an array, but what is
<T: Comparable>
or[T]
or even justT
? They are describing Generic data types. -
Singleton to Protocol
I was driving through the town of Singleton the other day and of course, it got me thinking about using singletons in my apps. Singletons were a commonly used pattern in Objective-C programming and appear in many of Apple's own APIs, but seem to be increasingly frowned upon in the Swift world.
So what is a singleton?
A singleton is a class that only expects to have a single instance. Think of it as a global instance of a class. In some cases this makes perfect sense if there can only ever be one instance of a particular class or if there is a default variant that suits most cases e.g.
-
Three Rules for Writing Better Swift
- Do not use !.
- Use let, not var.
- Allow the compiler to infer types.
Read on for more details...
-
Configuring Xcode
While not strictly a part of my Learning Swift series, today I thought I would discuss some of the ways to configure and use Xcode to be a more productive and comfortable programmer.
1. Editor color themes and fonts:
Step through the supplied themes and find the best one for you. Then click the '+' button at the bottom of the list and duplicate the selected theme. Now you can tweak it to suit you. Each text category can have its own font and size, but you can make multiple selections in order to do a bulk change. don't forget to check out the Console section too - I dislike the default bold text for many of the console reports, so always change that.