Joys
Joys

Reputation: 23

It is possible to do "if \(var1) = 0"?

var a = 0 

(... up to var z = 0)

let letterchoosedbyplayer:String = LetterChoosed.text!

"LetterChoosed" is a textbox. The player enter a letter in this textbox. I store the value in the variable "letterchoosedbyplayer". Then i want to check if the variable called 'letterchoosedbyplayer' (it must be a letter of the alphabet) is equal to 1. How can i do that? I want to do that :

if \(letterchoosedbyplayer) = 1 {          
}

Last Edit : All my code

let letterchoosedbyplayer:String = LetterChoosed.text!
if  Int(letterchoosedbyplayer) == 1 {
    print("vous avez perdu")
}
else {
switch letterchoosedbyplayer {

    case "a":
        print("lettre \(letterchoosedbyplayer) choisie")
        a = 1

    case "b":
        print("lettre \(letterchoosedbyplayer) choisie")
        b = 1

    default:
        print("cas défaut")
    }
}

Upvotes: 0

Views: 182

Answers (2)

vadian
vadian

Reputation: 285150

You could include the "1" case in the switch statement:

let letterchoosedbyplayer = LetterChoosed.text
if let lettrechoisie = letterchoosedbyplayer where !lettrechoisie.isEmpty {
    switch lettrechoisie {
        case "1": print("vous avez perdu")
        case "a":
            print("lettre \(lettrechoisie) choisie")
            a = 1

        case "b":
            print("lettre \(lettrechoisie) choisie")
            b = 1

        default:
            print("cas défaut")
    }
 }

Note that Int(letterchoosedbyplayer)! == 1 and letterchoosedbyplayer == "1" is the same thing.

Edit:

For your purpose you might use a dictionary rather than more than 20 single variables

var letterDict : [String : Int] = ["a" : 0, "b" : 0, "c" : 0, ... "z" : 0]

You can set a variable to 1 for example

letterDict["f"] = 1

Then you can check

if let lettrechoisie = letterchoosedbyplayer where !lettrechoisie.isEmpty {
    let value = letterDict[lettrechoisie]!
    if value == 1 { 
      // do something
    } else {
      // do something else
    }
}

That avoids also a huge switch statement.

Upvotes: 0

Johnykutty
Johnykutty

Reputation: 12839

\() is used to append any object in a string. I don't think you can use this for your need Try

if let letterchoosedbyplayer = LetterChoosed.text where letterchoosedbyplayer == "1" {
}

Upvotes: 1

Related Questions