Design Converter
Education
Software Development Executive - III
Software Development Executive - II
Last updated on Aug 5, 2024
Last updated on Jun 19, 2024
In the world of Swift programming, understanding Swift struct inheritance can dramatically improve your productivity and code quality. Frequently encountered while attempting to model simple data structures, Swift structures (or 'structs') and their inheritance patterns are indeed key concepts encompassing the Swift standard library.
Now you may find yourself asking, "But wait, what exactly is Swift struct inheritance?"
Well, as we dive into the core of this blog post, that's precisely what we'll be exploring.
Structures, referred to in Swift as "structs", are custom types provided by Swift that are used to store data. Much like classes in Swift (which we will discuss in the following sections), structs allow us to encapsulate data and behaviors into reusable blocks of code.
1struct SwiftStructsExample { 2 var nameProperty: String 3 int age 4}
In the above example, SwiftStructsExample is a struct that encapsulates two pieces of data: a string called nameProperty and an integer age.
We define a struct using the struct keyword. Each defined struct comes with a default memberwise initializer.
1var example = SwiftStructsExample(nameProperty: "Example Name", age: 5) 2print(example.nameProperty) 3print(example.age)
In this snippet, nameProperty and age are called stored properties. In Swift, you can create an instance of the struct using the default memberwise initializer, as shown above.
It's vital to distinguish structs from classes, primarily because they handle data differently. In Swift, structs (value types) and classes (reference types) are the building blocks for a data model. Furthermore, they also display different behavior when they're assigned to variables and constants.
For instance, if you assign a struct to a constant, the struct's properties are also constant. This behavior contrasts with classes, as even if a class instance is assigned to a constant, you can still modify class properties.
Swift encourages developers to use structs over classes when the data they are modeling doesn't need to inherit behaviors from other classes, or when they want to ensure that their data won't be modified. Here's a basic comparison:
1struct ValueExample { 2 var data: Int = 42 3} 4var value: ValueExample = ValueExample() 5value.data = 43 // Allowed 6let constantValue: ValueExample = ValueExample() 7constantValue.data = 44 // Error: Not allowed in Swift struct 8 9class ReferenceExample { 10 var data: Int = 42 11} 12let example: ReferenceExample = ReferenceExample() 13example.data = 43 // Allowed in Swift class
As you can see, this example highlights the differences in property behavior depending on whether we're dealing with a struct or a class.
The choice between struct and class isn't always straightforward, and it often depends on the nature of your data model.
However, it's often recommended to use structs for simpler, value-oriented data models, and classes when you need to take advantage of such things as inheritance or reference counting.
Classes in Swift allow for more advanced features compared to structs, such as inheritance and reference counting. This becomes crucial when you're dealing with complex data models that use multiple objects and relationships.
1class ExampleClass { 2 var name: String 3 var data: Int 4 5 init(nameProp: String, dataProp: Int) { 6 self.name = nameProp 7 self.data = dataProp 8 } 9} 10 11let instanceOfClass = ExampleClass(nameProp: "Example", dataProp: 42)
In the code above, we define a class with a custom init method rather than using the default initializer. The init method can be customized to set up the class instances in the way we want.
Class instances, as contrasted with structs, refer to the same underlying data. So, modifying data in one instance also affects other instances that point to the same data. Classes support inheritance, a mechanism where one class can inherit the properties and methods of another class.
While structs are ideal for creating small data models, the utility of classes cannot be overstated. They offer powerful tools for managing data in more complex codebases, supporting mechanisms like inheritance and reference counting.
With concepts like reference counting, classes give a more comprehensive grasp of managing and dealing with data. It's essential to capitalize on the methods and properties of classes and their instances to create complex, more functional, and sophisticated applications.
The suspense we created in the previous section was for a reason. Swift doesn't support direct struct inheritance.
Now, you may wonder, "Why did we title our blog Swift struct inheritance then?"
The answer lies in the power of protocols and extensions. Swift provides us with these tools which offer similar capabilities to a certain extent. Although a struct can't inherit from another struct or class, it can conform to multiple protocols. They describe a set of methods, attributes, and other criteria for a certain task or piece of functionality.
In Swift, you can use protocols to provide a default implementation of methods, and this is the nearest you can get to struct inheritance. Let's create an example:
1protocol DataProtocol { 2 var data: String { get set } 3 func displayData() 4} 5 6extension DataProtocol { 7 func displayData() { 8 print("Data: \(data)") 9 } 10} 11 12struct DataStruct: DataProtocol { 13 var data: String 14} 15 16let myData = DataStruct(data: "Swift Struct Inheritance") 17myData.displayData()
In this example, DataProtocol is a protocol that declares a data property and an instance method displayData(). We then create a default implementation for displayData() in the extension of DataProtocol. DataStruct is a struct that conforms to DataProtocol and therefore inherits the displayData method through the protocol's default implementation, not direct inheritance.
As we have mentioned, Swift structs provide a built-in memberwise initializer. But what if you want to customize this initialization process?
Swift allows you to provide your init method inside your struct. The structure could then be initialized with custom values rather than defaults. It provides you considerable flexibility over how your struct should be initialized.
1struct CustomInitStruct { 2 var data: String 3 var intProperty: Int 4 var stringProperty: String 5 6 init(int: Int) { 7 self.data = "Default data" 8 self.intProperty = int 9 self.stringProperty = "Default string" 10 } 11} 12 13let newStruct = CustomInitStruct(int: 42) 14print(newStruct)
In this struct, CustomInitStruct is defined with a custom initializer. The init method sets the data property to a default value, uses the passed int parameter to set the intProperty, and sets stringProperty to a default string. Now, let's discuss Swift classes and struct in the context of inheritance.
Swift is an intuitive and powerful language. It's expressive and swift (pun unintended!) in creating apps for the Apple ecosystem. Understanding the dichotomy between classes (reference types) and structs (value types), and their implications on data storage is not only fundamental to Swift but also imperative for an iOS developer.
Keep in mind, that structs have value semantics and do not support inheritance. The struct equivalent of class inheritance in Swift is realized through protocols and default implementations, which provide a considerable level of functionality.
To wrap up, while Swift struct inheritance may not be a standard feature like class inheritance, the use of protocols and extensions in Swift has made it fairly uncomplicated to share behavior across different structs. This understanding opens up new strategies for code organization, and reuse, and can lead to more understandable, maintainable, and flexible code.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.