Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I increase the scope of variables in switch-case/loops in Swift?

Tags:

swift

How can I use switch case statements that creates variables/constants that are valid outside of the switch-case statement. If there is no way to do that, what else can I do to achieve the same effect i.e. creating variables subject to a condition, and make it accessible in "global" or higher scope?

var dogInfo = (3, "Fido")

switch dogInfo {

case(var age, "wooff"):
    println("My dog Fido is \(age) years old")

case (3, "Fido"):
    var matchtrue = 10           --> 10
    matchtrue                    -->10

default:
    "No match"
}

matchtrue                       --> Error: Use of unresolved identifier 'matchtrue'

HERE IS HOW I SOLVED IT:

var randomNumberOne = 0, randomNumberTwo = 0, randomNumberThree = 0

func chosen (#a: Int, #b: Int) -> (randomNumberOne: Int, randomNumberTwo: Int, randomNumberThree: Int){

if a > 0 {
    let count1 = UInt32(stringArray1.count)-1
    let randomNumberOne = Int(arc4random_uniform(count1))+1
}

if b > 0 {
    let count2 = UInt32(stringArray2.count)-1                  Output: 3 (from earlier)
    let randomNumberTwo = Int(arc4random_uniform(count2))+1    Output: 2
}

if a > 0 && b > 0 {
    let count3 = UInt32(stringArray3.count)-1
    let randomNumberThree = Int(arc4random_uniform(count3))+1

}
return (randomNumberOne, randomNumberTwo, randomNumberThree)


}

chosen(a:0,b:1)                                              Output: (.00,.12,.20)

Great now I can index with this into an array! Thank you!

like image 936
KML Avatar asked Sep 21 '14 13:09

KML


People also ask

How do you use variables in a switch-case?

Some Important Rules for Switch Statements The value for a case must be of the same data type as the variable in the switch. The value for a case must be constant or literal. Variables are not allowed. The break statement is used inside the switch to terminate a statement sequence.

Can we declare variables in switch-case?

Declaring a variable inside a switch block is fine. Declaring after a case guard is not.

Which variables Cannot be used in switch-case statement?

The switch/case statement in the c language is defined by the language specification to use an int value, so you can not use a float value. The value of the 'expression' in a switch-case statement must be an integer, char, short, long. Float and double are not allowed.

How do you skip a switch-case in Swift?

You do this by writing the break statement as the entire body of the case you want to ignore."


3 Answers

There is no magic trick here. Swift uses block scoping and the switch creates a new scope to prevent errors and to show the programmer that the variables are only used in the scope. If you'd like to use the variables outside of the scope - declare these identifiers outside of the switch clause.

var dogInfo = (3, "Fido")
var matchtrue:Int = 0 // whatever you'd like it to default to
switch dogInfo {
case(var age, "wooff"):
    println("My dog Fido is \(age) years old")
case (3, "Fido"):
    matchtrue = 10           --> 10
    matchtrue                    -->10
default:
    "No match"
}
matchtrue     --> 10
like image 187
Benjamin Gruenbaum Avatar answered Jan 04 '23 12:01

Benjamin Gruenbaum


If matchtrue can contain a value or no value (if you do not initialize it) then you should use an optional variable declared before the switch:

var matchtrue: Int?

switch dogInfo {
    ...
    case (3, "Fido"):
        matchtrue = 10
    ...
}

if let matchtrue = matchtrue {
    // matchtrue contains a non nil value
}

You cannot define a variable inside a switch case if you want to use it outside - it would be the same as declaring a variable in a block of code and accessing from outside:

if (test == true) {
    var x = 10
}

println(x) // << Error: Use of unresolved identifier 'x'
like image 23
Antonio Avatar answered Jan 04 '23 10:01

Antonio


Here's a way. Paste this in a playground. You supply an age and a name and the different cases identify a match and return a tuple which contains a Match text and a value of the match.

func dogMatch(age: Int, name: String) -> (Match: String, Value: Int)  {

    switch (age, name) {
    case(age, "wooff"):
        println("My dog Fido is \(age) years old")
        return ("Match", 1)
    case (3, "Fido"):
        return ("Match", 10)
    default:
        return ("No Match", 0)
    }
}


dogMatch(3, "Fido").Match
dogMatch(3, "Fido").Value
like image 32
Steve Rosenberg Avatar answered Jan 04 '23 11:01

Steve Rosenberg