-2

I am moving a card game written in Objective-C to Swift. I have 2 arrays in my Hand class, both of size 3, one holding the 3 side-by-side down cards and the other holding the up cards that are on top of the down cards. The up cards and the uncovered down cards could be played, and so the arrays might hold some cards and have some elements nil, because the array cells are handling the actual positions of the cards. These are declared as

    var downCards: [Card] = []
    var upCards: [Card] = []
    downCards.reserveCapacity(3)
    upCards.reserveCapacity(3)

In Objective C, the following code, to tell me if there was an uncovered down card, worked fine:

    if ((handOfCurrentPlayer.upCards[cardLeft] == nil) &&
        (handOfCurrentPlayer.downCards[cardLeft] != nil)) {}

But in Swift, I get "Comparing non-optional value of type 'Card' to 'nil' always returns false"

I'm quite new to Swift, and can't figure out how to either declare the arrays differently or use optionals and unpacking to be able to check for missing cards (in other words, nil).

  • You might want to make a `struct CardSlot { let top: Card? ; let bottom: Card? }`, and then just make a single array of 3 non-optional `CardSlot` elements. – Alexander Aug 10 '20 at 20:23
  • Hello and welcome to SO. I would recommend cleaning up the description of your project and instead focus on the code, what isn't working etc. Use dummy names for variables where appropriate to make the question more neutral. Also, I would recommend specifying your question so as to expect to receive a single answer. There are multiple ways to avoid that error and some users may view this as a "fix this for me" question instead of requesting genuine insight. – Sanzio Angeli Aug 10 '20 at 22:36

1 Answers1

2

If the arrays can contain nil elements you have to declare the arrays with optional type

var downCards: [Card?] = []
var upCards: [Card?] = []
vadian
  • 274,689
  • 30
  • 353
  • 361
  • This worked fine. I had tried var downCards: [Card]?, which of course didn't work. Thanks for the quick answer! – BillDay Aug 10 '20 at 20:13
  • In Swift, a variable cannot contain nil unless its type is Optional. The same goes for the elements in an array. Think of an Optional as a box. The box can be empty, or contain an object. You can have an array contain Optionals. You have to open the box (unwrap the optional) before you can view it's contents. – Duncan C Aug 10 '20 at 20:36