My Books
-
Structs vs Classes
One of the big debates among Swift developers is when to use
structs
and when to useclasses
.Classes are the building blocks of object-oriented programming but structs as provided by Swift are newly powerful. Structs have been around in C-based languages for a long time, but Swift has made them more powerful and given them more features so that they are almost indistinguishable from classes. So what are the differences and which one should you use?
Where they are the same?
- both can define initializers
- both can define properties
- both can define methods
- both can conform to protocols
Where they are different?
- classes can inherit from other classes
- structs cannot inherit from other structs
- classes are reference types
- structs are value types
The reference type vs value type difference is where things really get interesting. Have a look at this example of a class with a single property:
-
Learning Swift - Optionals
-
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.