Create quick array expansion for typed arrays

New to Swift.

I am trying to extend the 'Array', where it contains objects of a known user type - "Job". The Job object contains parameters such as id, creationDate, title, etc.

I create an array of these job objects, for example.

var jobArray: [Job] 

Then I hope that

 let singleJob = jobArray.job(id: 123) 

and

 let completedJobs = jobArray.completedJobs() 

It seems the best way to do this is to simply extend the Array (preferably Array), then I can create some convenient functions for filtering and returning the corresponding jobs from the array.

I have tried many methods, but I think that I am closest to what I want to achieve here;

 extension Array { func job<T: Job>(id: Int) -> Job? { // Constrains this function to [Job] arrays? return filter{ ($0 as Job).id == id }[0] as Job } } 

I was hoping that by restricting the function to work only with certain arrays, which I could just pass to this type, and filter with variables, but instead it complains that "T cannot be converted to Job". This is understandable, but I also hope to perform a more global function as follows:

 extension Array { func availableJobs<T: Job>() -> [Job] { return filter { ($0 as Job).awarded == nil && ($0 as Job).completed == nil } as [Job] } } 

Is there a way to make my shortened version work, or am I completely wrong about this?

I managed to get something traditionally verbose by creating a new temporary array, repeating it manually, and then filtering it out, but it all seemed completely lengthy and unnecessary. If I could extend Array (for this type), all of this would be so simple - sad, it seems that this is simply not allowed (yet?).

I appreciate that maybe I'm trying to simplify something that can't be so; Swift shows so many promises, but maybe I need to wait until it ripens a little more?

Any ideas? ...

Thanks for any input.

0
source share

Source: https://habr.com/ru/post/1201667/


All Articles