Home > Enterprise >  How do you exchange values in tuples with each other using an intermediate tuple?
How do you exchange values in tuples with each other using an intermediate tuple?

Time:10-31

var human1 = (name: "Mike", age: 17, city: "NYC")
let oneHumanName = human1.name; let oneHumanAge = human1.age; let oneHumanCity = human1.city

var human2 = (name: "Amy", age: 15, city: "LA")
let twoHumanName = human2.name; let twoHumanAge = human2.age; let twoHumanCity = human2.city

How do you exchange values in tuples with each other using an additional intermediate tuple?

CodePudding user response:

Edit OK I misread the question. I'll leave my original answer below because it's better. This is how you do it with an intermediate tuple.

var human1 = (name: "Mike", age: 17, city: "NYC")
var human2 = (name: "Amy", age: 15, city: "LA")

let intermediate = human1
human1 = human2
human2 = intermediate

Without an intermediate

You can have tuples of tuples so the following will work:

(human2, human1) = (human1, human2)

Here is an example

var human1 = (name: "Mike", age: 17, city: "NYC")
var human2 = (name: "Amy", age: 15, city: "LA")

print("human 1 = \(human1)")
print("human 2 = \(human2)")

print("swapping")
(human2, human1) = (human1, human2)

print("human 1 = \(human1)")
print("human 2 = \(human2)")

Output:

human 1 = (name: "Mike", age: 17, city: "NYC")
human 2 = (name: "Amy", age: 15, city: "LA")
swapping
human 1 = (name: "Amy", age: 15, city: "LA")
human 2 = (name: "Mike", age: 17, city: "NYC")
  • Related