My original article — “Best Practices for Building Swift Classes” — was published on appcoda.com.
In this tutorial, I’m going to show you some best practices that will help you design and implement classes (reference types) and then safely leverage reference semantics in Swift. Protocol-oriented programming (POP) and value semantics are all the rage now, but a promising new technology doesn’t mean you should throw all your classes away. Why not add some simple constructs to your classes like copy initializers, default initializers, designated initializers, failable initializers, deinitializers, and conformance to the
Equatable protocol? To get real about my sample code, I’ll adopt these constructs in some classes and show you my best practices working in real life for drawing in your iOS app interfaces.
I’ll walk through the process of creating several protocols, creating classes that adopt those protocols, implement inheritance in these classes, and use instances of the classes (objects), all to illustrate my best practices — and to show some of the extra steps you may have to go through when working with classes.
Continue reading “Some best practices for designing and coding Swift classes”
My original article — “Protocol-oriented Data Structures in Swift 4: A Generic Doubly Linked List” — was published on appcoda.com.
Let’s talk about creating a list on steroids, i.e., a generic doubly linked list in Swift. For our purposes here, a list is a software receptacle that contains related data that we’re interested in inspecting, organizing, manipulating, etc. A doubly linked list stores a list of “nodes.” Each node contains data, knows about the preceding node in the list, and knows about the following node in the list. We’ll talk about adding nodes to the list, removing nodes from the list, displaying information stored in nodes in the list, and traversing the list. I’ve used the term generic because you’ll see that I can store store pretty much every built-in or custom Swift type in my linked list, like
CGAffineTransform… You can even store a collection of instances of a custom class or struct in my list (see section “Storing custom types” below). Most importantly, I’ll show you how to move towards generic programming, also known as generics, parametric polymorphism, templates, or parameterized types, where, when possible, we can write code that applies to many types, and thus reduces code redundancy.
Continue reading “Building a generic doubly linked list using protocol-oriented Swift 4”
Those of you who’ve used Objective-C and Swift for any meaningful length of time must be familiar with the
self property of structs and classes. I’m not sure how many are aware of the
Self “type” (sometimes called a “requirement”). I would be very interested in knowing how many understand the difference between
Self. I’m talking about
self with lower-case “s,” which I’ll call “small self” herein. It’s pretty well documented. Similarly,
Self with an upper-case “S,” is what I’ll call “tall self” herein. It’s not very well documented.
Continue reading “Self versus self in Swift 4 – capital “S” and lowercase “s””
Notice that Swift almost seems to frown on making a copy of a reference type, i.e., a copy of an instance of a class, or, as some would rather put it, getting a copy of an object. I’m not talking about getting another reference to a class, I’m talking about getting an entire, separate copy of a class instance. This frowning on class copying is not an accident. Swift’s language architects want the syntax and semantics of the language to be crystal clear. They want developers to be confident that reference types and value types will both have 1) distinct and obvious meanings and that both types will 2) behave consistently. But still, why not be able to safely make a copy of a class instance? I’ll show you how in this tutorial by borrowing the copy constructor concept from C++. In Swift, we’d call this a “copy initializer.” (NOTE: Yeah, yeah, yeah, I know about
NSCopying in Cocoa and Objective-C.)
Continue reading “Class copy constructors in Swift 4 for defensive copying”
The code shown herein will only compile and link in Xcode 10 beta and run on iOS 12 beta and/or OS X 10.14 beta.
While working on a Swift protocol-oriented and generic linked list, I got to thinking about Apple’s “improvements” to version 4.2 of their flagship language. Since a linked list is a list, I thought, “Why not add a subscript to my linked list to facilitate finding specific nodes in my list?” I did that in Swift 4.1 and got what most developers would’ve expected, e.g., used
linkedList["node4"] to get the node in the list associated with the keyword “node4.” With Swift 4.2, I can use the controversial new
@dynamicMemberLookup language attribute and implement dot/member notation, like
Continue reading “Swift 4.2 improvements? Member/dot syntax for subscripts. Trying it out in a protocol-oriented, generic linked list.”
In this tutorial, I’ll show you how to track down memory leaks within Xcode via the Memory Graph Debugger, new since Xcode 8. This is a powerful visual tool and doesn’t require you to step out of Xcode and start the Leaks Instrument. Once we identify some memory leaks, I’ll show you how to plug those leaks by using the Swift language’s
unowned qualifiers, and talk about the differences between the two qualifiers.
I recently discussed iOS memory management and memory leaks that occur when using reference semantics and reference types (classes) in my tutorials on “Swift 4 memory management via ARC for reference types (classes)” and “Fixing memory leaks — strong reference cycles — in Swift 4.” After reading these articles, you should understand how easy it is to inadvertently encode and introduce a strong reference cycle into your Swift 4 code and thus end up with a memory leak. You should also understand how generally straightforward it is to fix such a memory leak. My sample code in both tutorials was didactic. What about real-world projects with hundreds of thousands or millions of lines of code? Suppose that you’ve heard reports of diminished app performance, low memory warnings, or just plain app crashes. Finding memory leaks in your code is quite cumbersome when trying to debug via rote inspection, setting breakpoints, adding logging statements, etc.
Continue reading “Finding memory leaks with the Xcode Memory Graph Debugger and fixing leaks with unowned and weak”
PREREQUISITES FOR THIS TUTORIAL
If you don’t understand how Swift manages memory for classes (reference types), you need to read the first article in this series, “Swift 4 memory management via ARC for reference types (classes)”. Once you understand how reference type-based memory is managed with ARC, you’ll be ready to understand how to prevent memory leaks from occurring in your app. Remember that ARC only applies to reference (
class) types, not value types like
THE ARC DEALLOCATION PROCESS
Remember how we visualized the reference count that ARC maintains on the allocated instance of reference type
Widget in my introductory ARC tutorial?
// reference count is zero; nothing allocated
widgetReference = Widget(name: "eraser", manufacturer: "Acme")
// reference count is now 1
widgetReference1 = widgetReference
// reference count is now 2
widgetReference2 = widgetReference
// reference count is now 3
widgetReference = nil
// reference count is now 3-1 = 2
widgetReference1 = nil
// reference count is now 2-1 = 1
widgetReference2 = nil
// reference count is now 1-1 = 0
Continue reading “Fixing memory leaks — strong reference cycles — in Swift 4”
Most developers assume that Swift is a “safe” language in terms of memory management. That’s probably true most of the time, but there are some notable exceptions, especially when dealing with certain scenarios when using what are called “reference types” and “reference semantics.”
This tutorial is ultimately meant to prepare you for in-depth discussion of what seems to be inevitable shift from reference semantics to value semantics. Before I plunge into this software development paradigm shift, I want to provide you with a strong and understanding of how memory is managed when you create and use instances of the
class type, a reference type. Oftentimes, reference-based memory management “just works” … until it doesn’t. Things don’t work mainly in situations where
class types are designed with interdependencies and/or when multiple threads access the same instance (object) of a
class type, and you get “memory leaks.” Swift manages reference-based memory with a technology Apple has dubbed “Automatic Reference Counting” (ARC). Before even begin talking about debugging memory leaks, you must understand ARC.
This discussion does not pertain to memory management for value types (
enum), but note that I will mention value types and value semantics several times in terms of comparison to reference types and reference semantics.
Continue reading “Swift 4 memory management via ARC for reference types (classes)”