How to Create a Generic Array Extension That Sums Number Types in Swift

How can we create a generic Array Extension that sums Number types in Swift?

As of Swift 2 it's possible to do this using protocol extensions. (See The Swift Programming Language: Protocols for more information).

First of all, the Addable protocol:

protocol Addable: IntegerLiteralConvertible {
func + (lhs: Self, rhs: Self) -> Self
}

extension Int : Addable {}
extension Double: Addable {}
// ...

Next, extend SequenceType to add sequences of Addable elements:

extension SequenceType where Generator.Element: Addable {
var sum: Generator.Element {
return reduce(0, combine: +)
}
}

Usage:

let ints = [0, 1, 2, 3]
print(ints.sum) // Prints: "6"

let doubles = [0.0, 1.0, 2.0, 3.0]
print(doubles.sum) // Prints: "6.0"

How do I add two generic values in Swift?

protocol Numeric {
func +(lhs: Self, rhs: Self) -> Self
}

should be enough.

Source: http://natecook.com/blog/2014/08/generic-functions-for-incompatible-types/

Extension of constructed generic type in Swift

Swift 5.x:

extension Array where Element == Int {

var sum: Int {
reduce(0, +)
}
}

Wrapping a generic method in a class extension

You have to define the method for an array of optional elements, and the return type as the corresponding array of non-optionals. This can be done with a generic function:

extension Array {
public func removingNilElements<T>() -> [T] where Element == T? {
let noNils = self.compactMap { $0 }
return noNils
}
}

Example:

let a = [1, 2, nil, 3, nil, 4]   // The type of a is [Int?]
let b = a.removingNilElements() // The type of b is [Int]
print(b) // [1, 2, 3, 4]

In your code, $0 has the (non-optional) type Element, and it just wrapped by the compiler into an optional in order to match the argument type of compactMap().

How to implement generic function for adding both numbers and String in Swift?

One possible solution is this. You know you want your method to be applicable to anything that has a + defined... So define an explicit protocol. Let's call it Addable:

protocol Addable {
static func +(lhs: Self, rhs: Self) -> Self
}

Now, using extensions, declare conformance to Addable for the types you care about:

extension String: Addable {}
extension Int: Addable {}
extension Double: Addable {}

And define your add function as:

func  add<T: Addable>(first: T, second: T) -> T {
return first + second
}

Extending Array with generic floating point math type

It's impossible to say what the problem is exactly, because we don't know how your FloatingPointMathType protocol is defined. There are a few issues in your implementation (chiefly, you don't want to define a generic function mean<Element>; the extension is already parametrized over the Element type, and the generic parameter is introducing a new type name that shadows it (and that new type is unbound, so you can't do anything with it).

The following works with the standard library's FloatingPoint protocol:

public extension Collection where Element: FloatingPoint {
func mean() -> Element {
reduce(into: 0, +=) / Element(count)
}
}

Sum of Array containing custom class (Swift)

You can use a single reduce on array.

let sumOfValues = array.reduce({$0 += ($1.value ?? 0)})


Related Topics



Leave a reply



Submit