Bird
0
0

You have a tuple representing a book: (title: String, author: String, year: Int). How do you swap the title and author values in Swift?

hard📝 Application Q8 of 15
Swift - Data Types
You have a tuple representing a book: (title: String, author: String, year: Int). How do you swap the title and author values in Swift?
Avar book = (title: "Swift Guide", author: "John Appleseed", year: 2023) (book.title, book.author) = (book.author, book.title)
Bvar book = (title: "Swift Guide", author: "John Appleseed", year: 2023) book = (book.author, book.title, book.year)
Cvar book = ("Swift Guide", "John Appleseed", 2023) (book.title, book.author) = (book.author, book.title)
Dvar book = (title: "Swift Guide", author: "John Appleseed", year: 2023) book.swap(title, author)
Step-by-Step Solution
Solution:
  1. Step 1: Understand tuple with named elements

    Tuple has named elements title, author, year. To swap title and author, assign them in a tuple swap.
  2. Step 2: Check syntax for swapping

    var book = (title: "Swift Guide", author: "John Appleseed", year: 2023) (book.title, book.author) = (book.author, book.title) correctly declares named tuple and swaps title and author using tuple assignment.
  3. Step 3: Analyze other options

    var book = ("Swift Guide", "John Appleseed", 2023) (book.title, book.author) = (book.author, book.title) lacks names, so title and author don't exist as properties. var book = (title: "Swift Guide", author: "John Appleseed", year: 2023) book = (book.author, book.title, book.year) changes order but loses names. var book = (title: "Swift Guide", author: "John Appleseed", year: 2023) book.swap(title, author) uses invalid swap method.
  4. Final Answer:

    var book = (title: "Swift Guide", author: "John Appleseed", year: 2023) (book.title, book.author) = (book.author, book.title) -> Option A
  5. Quick Check:

    Swap named tuple elements with tuple assignment [OK]
Quick Trick: Swap tuple elements by assigning a tuple of swapped values [OK]
Common Mistakes:
  • Trying to swap unnamed tuple elements
  • Using invalid methods like .swap()
  • Reassigning tuple without names

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes