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?
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.
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.
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)
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With