有没有办法在Swift中交换两个不同的对象

iSh*_*lan 3 swift swift2 swift2.1

我想知道是否有办法在swift中交换两个不同的对象.

这是我的试用期:

func swapXY<T>(inout first: T,intout second: T)
{
    (first ,second  ) = ( second,  first)
}
Run Code Online (Sandbox Code Playgroud)

假设我希望这两个参数分别为T,Y.如何实现这一目标?

谢谢

Mr *_*ley 8

是的,您可以交换两个项目,该功能已包含在标准库中.

swap(_:_:)

Exchange the values of a and b.
Declaration

func swap<T>(inout _ a: T, inout _ b: T)
Run Code Online (Sandbox Code Playgroud)

Swift标准库函数参考

但是,如果它们不是同一类型,那么不,你不能交换两种不同类型的项目.

斯威夫特3

func swap<swapType>( _ a: inout swapType, _ b: inout swapType) {
  (a, b) = (b, a)
}
Run Code Online (Sandbox Code Playgroud)


Mac*_*tle 5

您可以做的是对从共同祖先继承的类进行更具体的交换:

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)")
Run Code Online (Sandbox Code Playgroud)

上面的代码可以工作,因为在交换之前和之后,catdog都为“ is-a” Animal。但是,交换无关类型的对象不能在Swift中完成,也没有任何意义:

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!
Run Code Online (Sandbox Code Playgroud)

该代码无法编译,因为类型变量Dog不能容纳CatSwift或任何其他强类型语言中的类型值。