Having lots of experience in Java, i am new to ios and swift and looking for directions.
In java i use to create DataObjects (like Point,person etc...) every one in different class file (*.java)
public class GamePreferences
{
int gameId;
int developerId;
String orientation;
}
In Swift i see many examples where classes are being written inside the View Controller
Is it really how it should be done? or should i create different files for this purpose? if yes what is the file types suited for defining classes?
Writing every class in a different .swift file is better way.
I prefer to write many classes in the same file only if the class is ridiculously small or related only to one class that is the main class in the file.
The advantages of every class in a different files are,
Easier to navigate and improve readability
Great granularity when working with version controls.Wspecially those where you have a locking checkout mechanism for editing files
Easier for new developers to find the appropriate classes
how do i import them to classe for me to use?
in Swift, you don't need to import classes. Simply use it. Only you need to import your external modules (targets), if any.
I've seen people create enums and structures inside the UIViewConroller class but never entire classes inside this.
You definitely should create separate classes, hopefully in separate files. It's not a limitation of the system.
In most examples, you see classes in the same file as the ViewController because it's easier to scroll through.
In a real life context, it depends on your preferences and/or project norms.
I prefer to split it in different files but it's totally up to you.
Related
We are doing some changes in existing project of Objective-C. Now, we have to save and share to other classes which have different data for every class. So, there are 20 different classes, so, we are planning to create 20 model (NSObject) classes.
After checked this executing properly, seems not a good practise.
Its like each class data is completely different.
Can anyone suggest us, is it good to create 20+ model (NSObject)
classes or is there any better solution for this?
My question is about using final keyword im Swift code. I know that final helps compiler to compile code faster because of dynamic dispatch. So, if I definitely know that I will not inherit some of my classes, should I make all of them final?
There was this protective approach taught by the iOS Stanford course.
The approach was, define all your APIs private. It increases encapsulation. Later if you needed to give away something then remove the privacy.
Because it's bad to do it the other way around ie design something public and then later change it to private.
Similarly here, I think making a class final and then later deciding it shouldn't be final is better than making a class non-final, allowing multiple classes to subclass it and then later attempt to revert it back to final because of some design decisions.
You are fine to do so if you are 110% you won't attempt to subclass any of your 'final' classes, as your project won't compile if you do so.
The article below has some great information and should help you decide.
http://blog.human-friendly.com/the-importance-of-being-final
If your app or a framework uses a protocols over inheritance then you can define your class types as finals.
If you prefer to use an inheritance over protocols and your app or framework is tested with a Unit Tests then don't define your class types as finals when they are used for a dependency objects because they will not be able to be mocked.
I'm a newbie to Swift and iOS programming in general, and I'm currently getting my hands dirty building a Swift app. I have encountered this problem of where to put the Constants.swift file (which basically stores the constants used by the app), and the confusion is mainly caused by the MVC logic. I have two options that I deem somewhat reasonable.
Put Constants.swift outside of the MVC framework, so that it does not belong to any particular party. Rationale: this way it could be conveniently referenced by all the components.
Put Constants.swift in the controller. Rationale: Controller is application-specific, and so is Constants.swift. Model and View are generic and hence should not be used to store constants.
But I don't know which of the two above I should use, or if there are any better options. What do you all think?
I think you should separate the constants in the classes that have to do with them and access them like:
Configurations.Constants.width or Car.Constant.speed
You can use structs with static properties to store them.
Don't know if that is your case, and depends on the constants, but it is not common to have one file with ALL the constants of the program, or one file with constants that need to be accessed from all the other components, this could indicate a design problem. If you store them close to or in the classes related to them, you won't have a problem with Cocoa's MVC.
Wondering if you might be able to answer a very basic beginner question for me. I’m working through the Cocoa + Swift tutorial on Lynda and I’m a little confused about classes/objects.
Basically, I want to know why we have to create a new swift file for each new class we create.
As far as I know, you can create a new class within any .swift file in the project. My question is, why do we have to continually keep creating .swift files for each new class.
I’m wondering why there isn’t just one .swift file called AllClasses.swift that you can create all the classes in, for instance:
Within AllClasses.swift is the following code:
Class FirstClass : NSObject
Class SecondClass : NSObject
Class ThirdClass : NSObject
Class FourthClass : NSObject
As Opposed to:
Within FirstClass.swift is the following code:
Class FirstClass : NSObject
Within SecondClass.swift is the following code:
Class SecondClass : NSObject
Within ThirdClass.swift is the following code:
Class ThirdClass : NSObject
Within FourthClass.swift is the following code:
Class FourthClass : NSObject
I just want to know why we need to separate different code into files if it can be called from within any area of the project. In the case of a Mac application, it seems like almost everything could be done from within the AppDelegate.swift file.
This is a moronic question, but another hurdle that may be making object orientation a hard concept for me to fully grasp.
Maybe I can explain it in a somewhat amusing way:
In the beginning there was no concept of files and all code was in a single entity. Code within such entities was referenced by line numbers. Because everything was in one place it was easy to find what you wanted, even though programs were small. It was better than punch tape and so there was much rejoicing. We gotta do something about loading from cassette though.
But then someone discovered you could break up the code into separate parts called modules which was just as well as software was getting bigger. Man my 10MB hard drive is huge. Each module was a specialist and could call other specialists. It made your code easier to navigate. There was much rejoicing.
But then someone discovered object-orientation (OO) and files were cheap. Programs were so large now people were having a hard time finding that class that modelled the airspeed of an African Swallow in that multiple-class-containing file of 10000+ lines that maybe its time to start putting each class in its own file. Needless to say there was much rejoicing.
Then software had become so large that someone discovered source control which was most important when a team of coding scribes all meditated on a piece of software. Madness ensured for the brotherhood whose careless endeavour to write a program in one file of 30,000+ lines (research on African Swallows had grown to include European Swallows) even with OO, only lead to line conflict after line conflict during their attempts to check in changes into the source control system. There was much burning at the stake. Later revelations lead to breaking up the code into many texts or files was the way to avoid a lynching.
In summary, there is no rule to say you must have one file per class but its a good practice to do so mainly in the event your program grows to any reasonable size or complexity that navigation and maintenance of your code would become an issue if you do not.
It becomes more important when working with a team where as the number of authors working concurrently on any given file, the probability of source code commit conflict rises.
I believe the monks are studying their favourite colours and capital cities of countries now.
Some reasons:
Encapsulation / Access Control. It's a bad practice to contain several classes in the same file as you'll be able to access every single variable / method from that source file even if that is marked as private, as stated in Apple documentation:
Private access restricts the use of an entity to its own defining
source file. Use private access to hide the implementation details of
a specific piece of functionality.
Separating your classes in separate files helps the compiler to build faster. When Swift 1.2 compiler was released, incremental builds were introduced to speed up the build times. Files that are not edited are not compiled again on your next build:
Incremental builds — Source files that haven’t changed will no longer
be re-compiled by default, which will significantly improve build
times for most common cases. Larger structural changes to your code
may still require multiple files to be rebuilt.
Writing code well organized. Together with defining correctly the responsabilities of your classes (divide and conquer) that will help you (and your teammates, if any) to understand who does what and where. And, as commented in other answers, to make your source control management easier to track.
You don't have to define just one class per file, but I would suggest doing so. I recently worked on a project for a client where there were several classes in some source files, and where some classes were defined in files who's names didn't match the class names. (This was in Objective-C, so each "file" was really a pair of files, a .h header file and a .m implementation file, but logically they were one.)
It was confusing as h*ll, and I wasted a fair amount of time fumbling around trying to find things.
Defining one class per file and making your filenames and class names match exactly is a good convention. It's like having each school subject in a separate binder. When you need to find a class you know exactly what file to open to find it.
As good practice:
If the classes are unrelated, lengthy or used independently from other unrelated classes then they should be in separate files.
However, if the classes are tightly coupled with one another and are not lengthy then they could be in the same file.
This post also touches on this subject.
As a newbie I really agree it is difficult to get the classes and inheritance concepts.
But believe it is much better to handle code in separate documents, perhaps using MVC concept, rather than having this code in a single massive document.
My own experience, it clears out the clouds of your code.
I just want to add the observation that Swift's fileprivate access modifier actually sometimes requires putting many classes inside a single source file.
The "one class per source file" doesn't necessarily fit the design of Swift. For this reason, when I need to tightly control which properties I expose, I often have one very large source file for a single API.
The only alternative is to make a separate framework for each API and using internal fields.
I'm currently following this guide to create an iOS framework to reuse among my projects. But I encounter a bit of a problem, I hope someone can help me out.
Here is the short version of my question: is there any way that I can expose certain implementation files from the framework to allow the containing project to overwrite/extend it while exposing only header files for the rest of the framework?
Here are some more details of what I'm trying to achieve.
Inside my framework, I have 2 classes, one extends another:
FrameworkClassA : FrameworkClassB
Inside the project that uses this framework, I want to extend these 2 classes to add custom methods specific to that project. So I did:
ProjectClassA : FrameworkClassAProjectClassB : FrameworkClassB
This works fine. However, the problem is, at the same time, I also want:
ProjectClassA : ProjectClassB
Basically, think of it as B is always higher than A, any method available in B needs to be also available in A.
As far as I know, multiple inheritance in Objective C is not possible. There are workarounds using class composition but I'm not very familiar with it and it seems a bit complex for what I want to do here.
So I have a bit of an "idea", but not sure how to do it. I'm thinking to have this chain of inheritance inside the framework:
SAMPLE_PROJECT_ClassA : FrameworkClassA : SAMPLE_PROJECT_ClassB : FrameworkClassB
SAMPLE_PROJECT_ClassA & SAMPLE_PROJECT_ClassB implementation files will be mostly empty inside the framework. I then expose only header files for all the files inside the framework (including FrameworkClassA & FrameworkClassB) but make SAMPLE_PROJECT_ClassA & SAMPLE_PROJECT_ClassB implementation files visible and editable.
Then inside the project that uses the framework, I will not create new classes but instead put my custom codes inside SAMPLE_PROJECT_ClassA & SAMPLE_PROJECT_ClassB and everything will follow the inheritance hierarchy that I want.
Is this possible? Or what is the best way to achieve something like this? Any guidance on this would be greatly appreciated. Thank you in advance.
UPDATE 1: Attached diagram
Please find the diagram of what how the classes are related here:
http://oi58.tinypic.com/20st6ow.jpg
(sorry, not having enough reputation to upload an image. Maybe someone can vote this question up to help me out in the future? :-P)
In that diagram:
"F" is framework and "P" is project.
Black Arrow is inheritance
Blue Arrow is "potential" inheritance between P classes and F classes.
Eventually, I want to be able to access FHelperA, FHelperB and openMenu from PTableViewController.
Objective-C does not support multiple inheritance, so ProjectClassA can't inherit from both FrameworkClassA and ProjectClassB.
Some ideas:
Depending on how you would like to design your framework you may want to look into class clusters, where you can have one interface and multiple implementations. This is a good place to start Apple Documentation
You can have a 3 classes instead of 2, one base class with all the shared methods and your A and B for your separate ones.
Another idea would be to use categories to extend the functionality, i.e. the A classes could extend the B classes, though you A classes won't inherit from each other.
Also consider drawing the graph of how you would like you classes in your frameworks to related to each other as this will help a lot to think of the design.