Skip to content

Instantly share code, notes, and snippets.

@Xvezda
Last active December 4, 2018 08:48
Show Gist options
  • Save Xvezda/aee479f3169949bd9bb103b4b903f757 to your computer and use it in GitHub Desktop.
Save Xvezda/aee479f3169949bd9bb103b4b903f757 to your computer and use it in GitHub Desktop.
Swift "Swap" operator by using generics and extension
/* Copyright (C) 2018 Xvezda <https://xvezda.com/> */
/* MIT License */
func swap<T> (_ a: inout T, _ b: inout T) {
let temp: T = a
a = b
b = temp
}
infix operator <=>: AssignmentPrecedence
extension String {
static func <=> (left: inout String, right: inout String) {
swap(&left, &right)
}
}
var (foo, bar) = ("World", "Hello")
foo <=> bar // Swap
print("\(foo), \(bar)") // Hello, World
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment