-1

I have a generic array.

let array = arrayOfElements as! [T]

I want to add elements of the array using reduce function of Swift. How can I do this?

I am doing this.

let result = array.reduce(0, +)

It shows error

ambiguous reference to member '+'

6
  • Have a look at Apple's docs: developer.apple.com/documentation/swift/array/2298686-reduce
    – user5306470
    Nov 23, 2018 at 6:23
  • Could you describe in detail what you want to achieve? For now, you probably get that error, because the compiler does not know what T is, and if + is appliable to elements of type T. Anyway, that does not look like adding element to the array. It reduces the array to the single value (as the 'reduce' name implies). Nov 23, 2018 at 6:25
  • 1
    How would you expect the compiler to be able to sum a generic type?
    – Leo Dabus
    Nov 23, 2018 at 6:26
  • You T should have +
    – Satish
    Nov 23, 2018 at 6:26
  • 2
    Your generic Type would need to be constrained to the Numeric protocol
    – Leo Dabus
    Nov 23, 2018 at 6:27

2 Answers 2

2

How do you know that T is a type that can be added? T can be anything, can't it? What if T is Bool? True and False values can certainly not be added.

To be able to add Ts, the range of possible types for T must be limited. T must conform to the Numeric protocol. Since the Numeric protocol defines a + operator, we can be sure that whatever T is, as long as it conforms to Numeric, it can be added.

You could do something like this:

func sum<T: Numeric>(_ array: [T]) -> T {
    return array.reduce(0, +)
}

Or an extension:

extension Sequence where Element : Numeric {
    func sum() -> Element {
        return reduce(0, +)
    }
}

Note that in both cases, I have put a : Numeric constraint.

1

You can’t. T can be any type, including types that don’t have the + operator and/or can’t be created from the integer literal 0. Those requirements are provided by the Numeric protocol, so you can define your type parameter as <T: Numeric> to make this work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.