0

I used to write Models in swift projects in separate files and that what I usually see in others projects, but wouldn't be easier to put them in one file? I want to know which is the best practice and why we supposed to follow? here an example of separating them:

User.swift

import Foundation
class User: NSObject {
    var name: String?
    var email: String?
    var id: String?
}

Post.swift

class Post: NSObject {
    var id: String?
    var type: String?
    var imageUrl: String?
    var caption: String?
}
amjad
  • 1
  • 1
  • 2
    not related to your question but you should use structures, declare its properties constants and non optionals. – Leo Dabus Jul 11 '19 at 04:32
  • It's a matter of taste. You can use one file `Model.swift` for all models or separate files with the name of the objects. By the way *best practice*: It's not the best practice to declare all properties carelessly as optional and as variable. For example an `User` has certainly `name`, `email` and `id`. And in most cases you don't even need a `class` inheriting from `NSObject`. – vadian Jul 11 '19 at 04:33
  • 1
    One consideration is that as your project grows (more people, more features), people become increasingly likely to need to simulaneously modify this master model file, causing merge conflicts in git. Splitting these models into separate files allows people working on separate corners of the code to not step on eachothers' toes like that. – Alexander Jul 11 '19 at 04:39
  • @LeoDabus Interesting! why I should use structures instead of classes? – amjad Jul 11 '19 at 05:04
  • As per my opinion model class should write in a separate file for maintaining the structure of your code. refere: https://developer.apple.com/library/archive/documentation/General/Conceptual/DevPedia-CocoaCore/ModelObject.html – Jatin Patel Jul 11 '19 at 05:08
  • @amjad https://stackoverflow.com/a/24232845/2303865 – Leo Dabus Jul 11 '19 at 05:18

0 Answers0