benj
benj

Reputation: 61

whats wrong with this swift code? indexing a tuple

var xypos: (Int, Int) = (x: 0, y: 0)

var nextxy: (Int, Int) = (one: 1, two: 2)

if x == 7 {
    nextxy.one = 0
} else if y == 63 {
    nextxy.two = 0
}

I get an error saying tuple nextxy has no member one or two. Ive used the same syntax and copied out of a book.

Upvotes: 1

Views: 68

Answers (4)

fzh
fzh

Reputation: 688

This code is right:

var xypos: (Int, Int) = (x: 7, y: 0)
var nextxy: (Int, Int) = (one: 1, two: 2)

if xypos.0 == 7 {
nextxy.0 = 0
} else if xypos.1 == 63 {
nextxy.1 = 0
}
print(xypos,nextxy)//xypos:7,0 nextxy:0,2

if you want access tuple by instance

var xypos: (x: Int,y: Int) = (2,2)
var nexttxy:(one: Int,two: Int) = (1,2)
if xypos.x == 7 {
    nexttxy.one = 1
  }else{
    nexttxy.two = 0
 }
print(xypos,nexttxy)//xypos:(2,2) nexttxy:(1,0)

for more information about tuple

Upvotes: 2

Rob Napier
Rob Napier

Reputation: 299703

You're forcing the type of nextxy to be (Int, Int), but you're expecting it to be type (one: Int, two: Int). Tuple labels are a weak part of the type in Swift, and are easily lost (one reason that structs are usually a better tool than tuples). Swift is willing to add or throw away tuple labels as it needs to (in many cases they basically act like comments).

If you let type inference do its job (which you should anyway), then you'll get the behavior you're looking for, though:

var nextxy = (one: 1, two: 2)

Now the type of nextxy is (one: Int, two: Int), which is what you're expecting.

Upvotes: 1

Bart
Bart

Reputation: 1268

And this should be ok as well:

var xypos: (x: Int, y: Int) = (x: 0, y: 0)

var nextxy: (one: Int, two: Int) = (one: 1, two: 2)

if xypos.x == 7 {
    nextxy.one = 0
} else if xypos.y == 63 {
    nextxy.two = 0
}

Upvotes: 1

hacker_1989
hacker_1989

Reputation: 303

if x == 7 {
    nextxy.0 = 0
} else if y == 63
    nextxy.1 = 0
}

This is what you need to do to fetch values at index.

Upvotes: 1

Related Questions