Amulya
Amulya

Reputation: 182

Generic Addition Function Swift

I want to make a function which could take two parameters and based on the type of the input it should perform binary operation(E.g. 'int' simple addition , for string it should concatenate etc..) and return the result . I am getting errors like "Binary operator ‘+’ can not be applied to two ’T’ operands" for following method

func commonAdd <T>(paramA:T,paramB:T)->T

Upvotes: 1

Views: 2023

Answers (3)

Parth
Parth

Reputation: 636

Conform AdditiveArithmetic Protocol for adding genric data type.

func commonAdd<T: AdditiveArithmetic>(paramA:T,paramB:T) ->T{
    return item1 + item2
  }

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 { "" }
}

Upvotes: 0

Deepak Deore
Deepak Deore

Reputation: 27

Generic function to add (Int, Double, String)

func add<T: Any >(itemA: T, itemB: T) -> T {

    if itemA is Int && itemB is Int {
        debugPrint("Int")
        let intNum1 = itemA as! Int
        let intNum2 = itemB as! Int
        return intNum1 + intNum2 as! T
        
    } else if itemA is Double && itemB is Double {
        debugPrint("Double")
        let doubleNum1 = itemA as! Double
        let doubleNum2 = itemB as! Double
        return doubleNum1 + doubleNum2 as! T
    } else {
        debugPrint("String")
        let string1 = itemA as! String
        let string2 = itemB as! String
        return string1 + string2 as! T
        
    }
    
}

Upvotes: -2

Luca Angeletti
Luca Angeletti

Reputation: 59526

A possible approach.

1) The Addable Protocol

You define an Addable protocol.

protocol Addable {
    func add(other:Self) -> Self
}

2) The commonAdd function

Next you define you function this way

func commonAdd <T: Addable>(paramA:T,paramB:T) -> T {
    return paramA.add(paramB)
}

3) Making Int conform to Addable

Next you pick a Type and made it conform to Addable

extension Int: Addable {
    func add(other: Int) -> Int {
        return self + other
    }
}

4) Usage

Now you can use your function with Int.

commonAdd(1, paramB: 2) // 3

More

You should repeat the step 3 to make Addable every Type you want to use in your function.

Upvotes: 3

Related Questions