Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to swap two different objects in Swift

Tags:

swift

swift2

I am wondering if there is a way to swap two objects of different types in Swift.

Here is my trial:

func swapXY<T>(inout first: T,intout second: T)
{
    (first ,second  ) = ( second,  first)
}

Let's say I want the two parameters to be T,Y respectively. How can this be accomplished?

like image 460
iShaalan Avatar asked Nov 10 '15 23:11

iShaalan


People also ask

How to swap element in array Swift?

In the Swift array, we can swap the position of the elements. To do so we use the swapAt() function. This function swap two values of the array at the given position.

How do you swap objects in JavaScript?

You can swap any number of objects or literals, even of different types, using a simple identity function like this: var swap = function (x){return x}; b = swap(a, a=b); c = swap(a, a=b, b=c); This works in JavaScript because it accepts additional arguments even if they are not declared or used.


2 Answers

Yes you can swap two items, and the function is already included in the standard library.

swap(_:_:)

Exchange the values of a and b.
Declaration

func swap<T>(inout _ a: T, inout _ b: T)

Swift Standard Library Functions Reference

However, if they are not the same type, then no, you cannot swap two items of different types.

Swift 3

func swap<swapType>( _ a: inout swapType, _ b: inout swapType) {
  (a, b) = (b, a)
}
like image 123
Mr Beardsley Avatar answered Nov 15 '22 10:11

Mr Beardsley


What you can do is a much more specific swap of classes inheriting from a common ancestor:

class Animal {}
class Dog: Animal {}
class Cat: Animal {}

// Note that cat and dog are both variables of type `Animal`, 
// even though their types are different subclasses of `Animal`.
var cat: Animal = Cat()
var dog: Animal = Dog()

print("cat: \(cat)")
print("dog: \(dog)")

swap(&dog, &cat) // use the standard Swift swap function.

print("After swap:")
print("cat: \(cat)")
print("dog: \(dog)")

The above code works because cat and dog are both "is-a" Animal, both before and after the swap. Swapping objects of unrelated types, however, cannot be done in Swift, nor does it really make sense:

var dog = Dog() // dog is of type Dog, NOT Animal
var cat = Cat() // cat is of type Cat, NOT Animal
swap(&cat, &dog) // Compile error!

This code won't compile because a variable of type Dog cannot hold a value of type Cat in Swift or any other strongly-typed language.

like image 27
TotoroTotoro Avatar answered Nov 15 '22 12:11

TotoroTotoro