swiftintegertogglevaralternate

how to toggle the value of a int variable


I want to use a toggle to change the value of int var punch card from 0 to 1. I am pretty sure there is a way to alternate this. I know it uses the : but I have forgotten it. It would also be cool if you could alternate between 0 1 2. I would think that is pretty easy once you get the 0 and 1 to work.

 var punchCard = 0

        @objc func memephis(){
        punchCard : 0: 1
        
    }

Solution

  • There are a couple of ways you can combat your issue. You could use a Boolean value & get it's integer value as they can be converted to 0 (false) or 1 (true).

    var punchCard: Bool = true // 1
    punchCard.toggle() // Will change between the value
    print(punchCard.intValue) // 0
    
    extension Bool {
        var intValue: Int {
            return self ? 1 : 0
        }
    }
    

    However you could too use a ternary-operator.

    var punchCard = 0
    
    func memephis() {
       punchCard = punchCard == 0 ? 1 : 0
    }