Extension of constructed generic type in Swift

前端 未结 7 730
闹比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:47

    This can be achieved using protocol extensions (See The Swift Programming Language: Protocols for more information). In Swift 3:

    To sum just Ints you could do:

    extension Sequence where Iterator.Element == Int {
        var sum: Int {
            return reduce(0, +)
        }
    }
    

    Usage:

    let nums = [1, 2, 3, 4]
    print(nums.sum) // Prints: "10"
    

    Or, for something more generic you could what @Wes Campaigne suggested and create an Addable protocol:

    protocol Addable {
        init()
        func + (lhs: Self, rhs: Self) -> Self
    }
    
    extension Int   : Addable {}
    extension Double: Addable {}
    extension String: Addable {}
    ...
    

    Next, extend Sequence to add sequences of Addable elements:

    extension Sequence where Iterator.Element: Addable {
        var sum: Iterator.Element {
            return reduce(Iterator.Element(), +)
        }
    }
    

    Usage:

    let doubles = [1.0, 2.0, 3.0, 4.0]
    print(doubles.sum) // Prints: "10.0"
    
    let strings = ["a", "b", "c"]
    print(strings.sum) // Prints: "abc"
    

提交回复
热议问题