Swift Array extension only for certain type of Array

57 views Asked by At

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
        }
    }

}
0

There are 0 answers