How to Add Two Generic Values in Swift

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/

Best way to sum two generic values in Swift

If you need to make sure your type can be summed all you need to do is to constrain your generic type to additivearithmetic

If you need to support Strings, make it conform to AdditiveArithmetic but you will need to implement subtraction as well:

extension String: AdditiveArithmetic {
public static func -= (lhs: inout String, rhs: String) {
var set = Set(rhs)
lhs.removeAll{ !set.insert($0).inserted }
}
public static func - (lhs: String, rhs: String) -> String {
var set = Set(rhs)
return lhs.filter{set.insert($0).inserted}
}
public static var zero: String { "" }
}

func sum<T: AdditiveArithmetic>(_ lhs: T, with rhs: T) -> T {
lhs + rhs
}

func subtract<T: AdditiveArithmetic>(_ lhs: T, from rhs: T) -> T {
rhs - lhs
}

print(sum(5, with: 4)) // 9
print(sum(5.5, with: 4.3)) // 9.8
print(sum("5", with: "4")) // 54
print(subtract("5", from: "12345")) // "1234\n"
"12345" - "5" // "1234"

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
}

Generic Sum for Numeric and String in Swift

To have one generic function for such a case you would need to find a common behavior that could be used as a constraint for a generic Type. In your case, you can do (but you should NOT) this:

DON'T DO THIS

extension String: AdditiveArithmetic {
// some stupid placeholders, as there is no obvious behavior for that :D
public static func - (lhs: String, rhs: String) -> String {
lhs
}

public static var zero: String {
""
}
}

func sum<T: AdditiveArithmetic>(_ a: T, _ b: T) -> T {
a + b
}

print(sum("LOl", "KEK")) // LOLKEK
print(sum(1, 2)) // 3

I would RECOMMEND just to add a new func for that particular case

func sum(_ a: String, _ b: String) -> String {
a + b
}

passing two generic types as function parameters

Looks like this will work

sample(String.self, to: Int.self)


Related Topics



Leave a reply



Submit