LettersBa
LettersBa

Reputation: 767

Differences between generic functions and the use of Any

I am currently learn the use of generic functions and realized the problem that they solve with some existing examples in the documentation.

So instead I keep repeating functions that perform the same scheme, I can use generic functions that way:

func swapTwoValues<T>(inout a: T, inout b: T) {
    let temporaryA = a
    a = b
    b = temporaryA
}

But if we think a little more we can use the command Any for that:

func swapTwoStrings(inout a: Any, inout b: Any) {
    let temporaryA = a
    a = b
    b = temporaryA
}

So, why use generic functions if we can do the job using Any?

Upvotes: 0

Views: 45

Answers (2)

Leo
Leo

Reputation: 24714

Using generic functions,here T is a type.In your code,it means that a and be should be same type.

func swapTwoValues<T>(inout a: T, inout b: T) {
    let temporaryA = a
    a = b
    b = temporaryA
}
var a = 1
var b = 2
var c = "1"
var d = "2"
var e = 1
var f = "2"
swapTwoValues(&a, &b)//rihgt
swapTwoValues(&c, &d) //rihgt
swapTwoValues(&e, &f) //Wrong

Use any,you do not know if a and b is same type or not.**So,if your function is complex,you have to dynamic check the type.**And there is also some difference when you using the two functions

func swapTwoAny(inout a: Any, inout b: Any) {
    let temporaryA = a
    a = b
    b = temporaryA
}

Then example 1

  var a = 1
  var b = "2"
  swapTwoAny(&a, &b)//Wrong

Example 2

var a = 1 as Any
var b = "2" as Any
swapTwoAny(&a, &b) //Right.

Upvotes: 1

Catfish_Man
Catfish_Man

Reputation: 41831

If you're just swapping things, there's probably no need to use generics over Any. If you actually intend to call any methods on the arguments though, you'll need to either cast them to a type that has those methods (verbose, can fail at runtime, slower), or use generic parameters.

Upvotes: 0

Related Questions