Constantine
Constantine

Reputation: 13

Accessing a member of a tuple

I'm curious how can I access a member of a tuple if some of the members have optional type

let serverResponse: (Int, String?, String?) = (statusCode: 255, message: "Welcome", errorMessage: "Error")
print(serverResponse.message)

I get an error

error: value of tuple type '(Int, String?, String?)' has no member 'message'

Upvotes: 0

Views: 96

Answers (3)

Sandeep
Sandeep

Reputation: 21144

The problem with your code is that you are defining, (Int, String?, String?) to (statusCode: Int, message: String, errorMessage: String) which are interchangeable.

If you leave the type definition empty for the variable, the type inference should provide you with the correct type.

let response = (statusCode: 255, message: "Welcome", errorMessage: "Error")
print(response.message)

Or, if you want to define the type make sure that the type is actually (statusCode: Int, message: String, errorMessage: String).

let response: (statusCode: Int, message: String, errorMessage: String) = (statusCode: 255, message: "Welcome", errorMessage: "Error")
print(response.message)

You could also use tuple de-structuring syntax,

let (_, message, _) = (statusCode: 255, message: "Welcome", errorMessage: "Error")
print(message)

Upvotes: 1

Shehata Gamal
Shehata Gamal

Reputation: 100503

You better use a struct for this

struct Response {
  let statusCode:Int 
  let message,errorMessage:String?
}

Then you can do

let item = Response(statusCode: 255, message: "Welcome", errorMessage: "Error")
print(item.message)

But with tuple use

print(serverResponse.1) // statusCode = 0 , message = 1 , errorMessage:String = 2

Upvotes: 1

Helge Becker
Helge Becker

Reputation: 3243

Either access them by their indices ($0, $1 etc) or expand the type.

let serverResponse: (statusCode: Int, message: String?, errorMessage: String?) = (statusCode: 255, message: "Welcome", errorMessage: "Error")

Upvotes: 0

Related Questions