2

If I want to make an Array extension, but only do an extension for an Array of type [UIView], is that possible in Swift?

Currently I'm just doing a normal extension Array with a precondition that the Array only holds elements of type UIView, but it seems like there must be a better way.

Here is how I'm currently doing it:

extension Array {

    mutating func sortByVerticalPositionTopToBottomIn(rootView: UIView) {
        precondition(arrayConsistsOfOnlyType(UIView), "This method should only be used for arrays of UIViews.")

        self.sort {
            let firstObj = $0 as! UIView
            let secondObj = $1 as! UIView
            return firstObj.convertPoint(CGPointZero, toView: rootView).y < secondObj.convertPoint(CGPointZero, toView: rootView).y
        }
    }

}
Paulw11
  • 108,386
  • 14
  • 159
  • 186
Adam Johns
  • 35,397
  • 25
  • 123
  • 176
  • 2
    That is still not possible (as far as I know), but in Swift 2 something *similar* can be done with "protocol extensions". In Swift 1.x you would need a global function. See (for example) the various answers to [Array extension to remove object by value](http://stackoverflow.com/questions/24938948/array-extension-to-remove-object-by-value) and [Is it possible to make an Array extension in Swift that is restricted to one class?](http://stackoverflow.com/questions/27350941/is-it-possible-to-make-an-array-extension-in-swift-that-is-restricted-to-one-cla) – Martin R Jun 12 '15 at 03:27
  • @MartinR not possible but something similar – you mean you can only extend the protocol not `Array` specifically? – Airspeed Velocity Jun 12 '15 at 04:39
  • @AirspeedVelocity: Yes, that's what I meant with "protocol extension". Let me know if my comment is wrong or if you disagree about the duplicate, then I'll reopen the question. – Martin R Jun 12 '15 at 04:41
  • @MartinR Was just checking that was what you meant as I interpreted similar to mean not quite what you want – personally I would say that means it _is_ possible since in this use case extending the protocol rather than Array specifically is just as good if not better. Agree its a dupe. – Airspeed Velocity Jun 12 '15 at 04:49

0 Answers0