How best to handle this situation

I have an array of classes. This class can take a NUMBER or a DATE (not a string)

it has two functions

func addPoint(x:CGFloat)
func addPoint(x:Date)

the problem is, it cannot be mixed… all number or all date

What I was thinking was to set a flag equal to the type of the first entry
and if an entry of a different type was made . throw an error

Any better ideas?

Add an array of points instead ?

I meant how should the app react if it gets a mixed value


You mean generics? Documentation

generics allow a function to accept “any” type, but that doesn’t solve the problem

Once the class has accepted one type (either number or date), it cannot accept the other type

is this a SWIFT thing? In Java, Go, Rust you can check the type of your generic and react accordingly otherwise generics won’t make much sense.

I think you are missing my situation


That would be allowed


That would be allowed


That would NOT be allowed

Generics won’t solve that, as addPoint can be make to accept either type… but once it has started to accept ONE type, it should then not be allowed to accept the other

Personally, I’d used the function name to indicate.

addCGPoint( inPoint: CGPoint )
addDatePoint( inDate: NSDate )

Or to help autocomplete.

1 Like

accept any type as input
in the addpoint method, check the parameter input type
if it is not one that is already in the point list of the method, then reject with an exception or an error code

I need the compiler to catch it at design time, not at runtime… but thanks

yeah catching error at compile time is preferable to catching them at runtime

catching things as early in the development process as you can lowers the cost of fixing them

I’ve re-read the thread and think I didn’t fully understand what you’re trying to accomplish.

So my thoughts are this.

  1. Context Switches of any kind in the addPoint function are not going to give you what you want, and they will consume CPU time when not needed.

  2. Subclassing should allow this. You create one subclass that can take a number, and one subclass that can take a date. You name the different functions for each subclass, this way at design time it’s clear which class you’re using and therefore you’re less likely to pass in a date to a class that doesn’t accept a date.

#2 is up and running quite nicely

1 Like