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.

1
  • Both the Swift and the Objective-C version have an if Commented Jan 18, 2017 at 16:51

2 Answers 2

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

}
2
  • For the protocol: The Objective-C piece of code isn't Objective-C'ish. Commented Jan 18, 2017 at 16:44
  • How does reduce the number of nested if? Commented Jan 18, 2017 at 16:51
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.
}
1
  • Thanks. I guess I got hung up on keeping the -1 return value. Optional value works as well.
    – Johnne
    Commented Jan 18, 2017 at 16:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.