Extension of constructed generic type in Swift

前端 未结 7 705
闹比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 15:03

    It is possible to return a real sum-value after you have tested for the int-type in sum(). Doing so I would solve the problem as follows:

    import Cocoa
    
    extension Array {
        func sum() -> Int {
            if !(self[0] is Int) { return 0; }
            var sum = 0;
            for value in self { sum += value as Int }
            return sum;
        }
    }
    
    let array = [1,2,3,4,5]
    array.sum() // =15
    
    let otherArray = ["StringValue"]
    otherArray.sum() // =0
    
    0 讨论(0)
提交回复
热议问题