4

I was looking at ways to convert a Array<T?> into an Array<T>? based on whether or not any of the items are null. One of the options I considered for doing this when I couldn't figure out a short way to do it was to create an extension method on Array for this, but I couldn't figure out how to do it.

How could I turn this method:

func toNonNullable<T>(array: [T?]) -> [T]? {
    if array.filter({$0 == nil}).count != 0 {
        return nil;
    }

    return array.map({$0!}) 
}

into an extension method on Array?

I am not asking if it would be a good idea to add this extension method (I'm not convinced it is), just how I could do it (if it's possible at all).

Community
  • 1
  • 1
Redwood
  • 66,744
  • 41
  • 126
  • 187
  • You cannot write a method on a generic type that is more restrictive on the template, compare http://stackoverflow.com/questions/24938948/array-extension-to-remove-object-by-value or http://stackoverflow.com/questions/24047164/extension-of-constructed-generic-type-in-swift. So you cannot define an extension method that applies only to arrays of an optional type. – Martin R Apr 28 '15 at 20:43
  • 1
    Sounds like that should be an answer, though I'll probably wait a while to accept in case somebody else can offer an alternative. – Redwood Apr 28 '15 at 20:46
  • Sure. If no better answer comes in then it could also be closed as a duplicate of one of the referenced questions. – Martin R Apr 28 '15 at 20:48
  • 1
    You would probably be better off with `if contains(array, {$0 == nil})` since this avoids creating an array that isn’t used, and also will exit out on hitting the first `nil` rather than checking all elements when the presence of one is all that’s needed. – Airspeed Velocity Apr 28 '15 at 23:44

0 Answers0