Pass in a type to a generic Swift extension, or ideally infer it

后端 未结 2 1576
猫巷女王i
猫巷女王i 2020-12-03 03:26

Say you have

 class Fancy:UIView

you want to find all sibling Fancy views. No problem...

    for v:UIView in sup         


        
2条回答
  •  既然无缘
    2020-12-03 03:45

    Similar answer to what's been said previously, but a little more streamlined and without having to pass anything or iterate over the subviews more than once:

    extension UIView {
        internal func siblings() -> [T] {
            return superview?.subviews.flatMap {return ($0 == self) ? nil : ($0 as? T) } ?? []
        }
    }
    

    or my preference using optionals:

    internal func siblings() -> [T]? {
            return superview?.subviews.flatMap {return ($0 == self) ? nil : $0 as? T } 
    }
    

    Example Usage:

    class ExampleView: UIView {
    
        func getMatchingSiblings(){
            let foundSiblings: [ExampleView] = siblings()
        }
    
        //or with the for loop in the question:
        for item: ExampleView in siblings() {
    
        }
    }
    

    When dealing with generics, you simply need one instance of the generic type in the signature of the method. So if you have either a parameter, or return type that uses the generic, you don't need to pass the type.

提交回复
热议问题