0

I have a model object and there are some properties in that object. Based on some conditions, I want a property to be defined there or not to be defined. For example, this property is my app version.

    class Person {

      var name: String
      var address: String
      var age: String

      // I want some condition here like if myAppVersion > 1.0 then add isChild 
      //  property to my model object other wise don't add that 

      var isChild: Bool

      // Normal property again
      var gender: String
    }

I want this behaviour because the properties are coming from the backend and all these properties are required, so if, for some reason, the BE doesn't send the a required property which the client is expecting, then I will crash. These properties have to be mandatory and not optional.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Madu
  • 4,849
  • 9
  • 44
  • 78

1 Answers1

3

Don't do this.

Declare your parameter as an optional and set it to nil if you don't want it to have a value. You should create two separate classes if you want to have different implementations, but that would be pretty superfluous for just one little change.

If your application crashes just because a property has a nil value, you should really take a look at optional handling in Swift and nullability in Objective-C.

Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
  • 1
    Agree with this. Your model property should still be optional even if it is required from a business-logic perspective. This will allow you to freely have different properties for different versions of the backend API. – davidethell Mar 12 '18 at 11:02