Reputation: 1
I have a class which I want to be reusable (for any developer user who wants it, or outside my project). This class returns a Struct
, let's call it structA
, and the class is classA
.
The first thought is to put structA
inside the same file of this class, so while the Struct
is public, any user who get this class file can read this Struct
which the class returns.
Till here it looks reasonable (or not).
But what happens if other classes in my current project also need to use this Struct
for other purposes? (a copy of it)
Then to make the code reusable I need to put this struct somewhere else. By reusable I mean there are no dependencies- get the class file and that is it.
If it's outside classA
, then classA
becomes not reusable and dependent.
If it's inside classA
, then other class that use it are also dependent (not reusable outside)
The only solution left is to create other Structs like this with different names (sounds bad).
Where would you put this Struct
in your Xcode project?
Upvotes: 1
Views: 227
Reputation:
Put your struct in a separate file and document for each class you want to reuse that it depends on this struct. So basically you make your struct reusable as well.
The process of reusing your class becomes a little bit harder - you also have to include it’s dependencies. But that is just a fact of life, basically all software has dependencies. To make it easier to add some code dependency manages such as Cocoapods, Carthage or the Swift Package Manager have been invented. With those you specify for each library what it depends on - so ClassA
depends on StructA
. In the project you want to use ClassA
you specify only that dependency and the package manager installs all of it’s dependencies (and their dependencies and so on) together.
Upvotes: 3
Reputation: 1693
You can create a separate library or framework which will contain all the reusable classes and structs.
Whenever you want to use the class classA
or the struct structA
, you can just import that library in the respective file.
Repeating the code is not recommended.
Upvotes: 1