Home > OS >  Accessing a member of a tuple
Accessing a member of a tuple

Time:11-24

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'

CodePudding user response:

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

CodePudding user response:

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")

CodePudding user response:

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)
  • Related