UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Project 10, Part 1

Forums > 100 Days of SwiftUI

I am not quite understanding why this data variable is declared as this: "let (data, _) = try await..."

rather than: "let data = try await..."

Is it becaue there are multiple variables being declared or something? Why is this syntax necessary? What does the _ represent?

   

If you check the Apple Documents for URLSession.shared.data(from: ) you will see that it return -> (Data, URLResponse) so you could do let (data, response) = .... however as you do not use the response anywhere you can use _.

1      

@MeruemMoniker wonders about return types:

Is it becaue there are multiple variables being declared or something?
Why is this syntax necessary? What does the _ represent?

Grocery Checkout

I visited the green grocers this week, at the checkout I received my bag of groceries, PLUS a paper receipt.

So in pseudocode, it might look like this:

// After the transaction, I get both the groceries and the receipt
let (groceries, receipt) = ShopTransaction( ...snip.....)

But most of the time, I am not bothered with the receipt, and I typically ignore it by dropping it in the rubbish bin. The underscore character represents the digital rubbish bin when a method offers you a value that you don't care about.

// After the transaction, I accept the groceries, but IGNORE the receipt
let (groceries, _) = ShopTransaction( ...snip.....)

In the case of Cupcake Corner, the URLSession.shared.data(from: url) returns a tuple with two variables. One is the data it extracted from the URL. The other variable is a response message.

In a bona-fide shipping AppStore application, you'll want to capture the response message and interpret it for your user. It may tell you the database is offline, or the user is not authenticated, or the request is invalid. You should capture this and take appropriate action.

Alas. Project 10 is just a teaching application so it focuses just on the returned data, ignoring the server response.

Don't Care about the Response

So when this method returns a tuple, you can simple toss the response into the digital rubbish bin. You do this by assigning the result to an underscore character ( _ ) . In essence you are telling the compiler that you recognize the method is returning a value, but you are ignoring it.

Keep Coding!

1      

https://www.hackingwithswift.com/forums/100-days-of-swiftui/project-10-part-1/26130/26131

Okay, this is all fine. But something else is interesting:

  1. Would you ever use the tuple anywhere, or do you just use the two pieces of data returned from it (data and response) appropriately for their respective use cases as is the case in project 10?

  2. Additionally, if you hypothetically could and had to use a data and response tuple, would you have to assign them to a variable like this: let dataResponse = (data, response) or would the unique signature of "(data, response)" be enough to use this tuple elsewhere without declaring it as a variable beforehand?

I may be getting sidetracked, but I'm truly wanting to understand better.

P.S. Nice analogy. Cemented the idea for me.

   

Would you ever use the tuple anywhere,

@twoStraws noted that a tuple is similar to a struct, but it doesn't have a name.

// Struct ===================
struct Programmer {
    name: String
    languange: String
}

let student = Programmer( name: "Meruem", language = "Swift")

// Tuple ==================
let student = (name:"Meruem" , language: "Swift")
print( "\(student.0) writes \(student.language) code) // note either use is ok!

// output is 
// Meruem writes Swift code"

We don't think of tuples very often in common daily logic. Often if we think we need an answer to a function call, we'll just return a struct that carries all the data we need.

A tuple allows the flexibility to return a simpler form of the data, with additional data if necessary.

Keep Coding

   

if you hypothetically could and had to use a data and response tuple,
would you have to assign them to a variable like this

If you use the form let dataResponse = (data, response), you have to understand that dataResponse is a variable of type tuple. It's not an Int. It's not a String. It's a tuple.

In this case, the tuple has two parts. Because you didn't give the two parts names, the compiler allows this form:

let dataResponse = (data, response)

print( dataResponse.0) // prints the data
print( dataResponse.1) // prints the response portion

Review

This might be a good time to review one of @twoStraw's articles.

See-> Structs versus Tuples

Integer Example

Here's an example of a tuple method on Integers. The integer object has a method named quotientAndRemainder that returns a tuple.

let divisor = 350

// EXAMPLE 1 =========================
// Note: answer is a named tuple with two parts.
var answer  = divisor.quotientAndRemainder(dividingBy: 4)
// Note 350 / 4 = 87, with a remainder of 2
print (answer.quotient)  // prints 87
print (answer.remainder) // prints 2

// alternativly, you could use this form...
print (answer.0) // prints 87
print (answer.1) // prints 2

// EXAMPLE 2 =========================
// Note the response type is an unnamed tuple.
let (quotient, remainder) = divisor.quotientAndRemainder(dividingBy: 5)
// Note 350 / 5 = 70, with a reminder of 0
print (quotient)  // prints 70
print (remainder) // prints 0

Keep Coding

Growing up, I thought quicksand was going to be a big problem in my life. I knew about quicksand, and possible ways to escape its terrible powers. Yet, to this day, quicksand has had very little impact on me. Tuples might be in the same family. Know about them, consider them. You probably won't interact with them much.

If you've read this far, please add to our understanding and give us an example of how you might use Tuples in your code.

   

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.