2

How would you convert this Objective-C

if ((loc = [player locateCardValue:8]) > -1) {

to Swift 3?

[player locateCardValue] returns an integer of the location where the card '8' was found. Returning -1 means it didn't find the card '8'.

I could use ...

let loc = player.locateCard(withValue: 8)
if loc > -1 {

but I have multiple nesting of IF's and it would get really messy.

Johnne
  • 143
  • 10

2 Answers2

5

Maybe the best approach is not to convert it "as is", but to make it more Swift-like.

In this case I think I would change the locateCard to return an Optional<Int> and return nil when the card is not found.

func locateCard(withValue: Int) -> Card? {
    // return the position if found, nil otherwise
}

Then, you can just write

if let card = player.locateCard(withValue: 8) {

}
Luca Davanzo
  • 21,000
  • 15
  • 120
  • 146
Marcos Crispino
  • 8,018
  • 5
  • 41
  • 59
2

Your best option is to convert locateCardValue to return an Optional Int?. Then you could simply do

if let loc = player.locateCard(withValue: 8) {
    // ...
}

Or you could use a switch statement

switch player.locateCard(withValue: 8) {
case -1: print("No card.")
case 1: // ...
// etc.
}
sdasdadas
  • 23,917
  • 20
  • 63
  • 148
  • Thanks. I guess I got hung up on keeping the -1 return value. Optional value works as well. – Johnne Jan 18 '17 at 16:51