Extension of constructed generic type in Swift

前端 未结 7 750
闹比i
闹比i 2020-12-02 13:56

Is it possible to extend an generic class for a specialised/constructed generic type? I would like to extend Int Arrays with a method to calculate the sum of its elements.

7条回答
  •  孤街浪徒
    2020-12-02 14:37

    you can do it as well

    extension Array {
        func sum () -> Int? {
            guard self.count > 0  && self.first is Int  else {
                return nil
            }
            var s = 0
            forEach {
                s += $0 as! Int
            }
            return s
        }
    }
    

提交回复
热议问题