How to Increase the Scope of Variables in Switch-Case/Loops in Swift

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

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

How can I expand the scope of a variable in Swift

As mentioned, you have two num1 variables. The 2nd one is scoped to just the block of the 2nd if statement.

You also have an issue that readLine returns an optional String, not an Int.

You probably want code more like this:

var num1: Int?

if userChoice == "add" {
print("Enter first number")
if let line = readLine() {
num1 = Int(line)
}
}

print ("\(num1)")

Of course you may now need to deal with num1 being nil.

One option is to properly unwrap the value:

if let num = num1 {
print("\(num)")
} else {
print("num1 was nil")
}

How to pass global variables through switch/case

Your code won´t compile first of all, you do get the error error: variable 'filter' used before being initialized

So declare filter as follow:
var filter = String() or var filter = ""

Secondly since you´re not adding all of your code I tried the following:

var filter = String()
let x = 0

switch x {
case 1:
print("1")
default:
filter = "value"
print(filter)
}
print(filter)

This prints out:

value
value

If you need further help update your question with more information.

Update:
Just tried your updated code:
var filter = String()
let arguments = ["qwe", "value", "qwe", "asd"]
print(arguments.count)
switch arguments.count {
case 1:
break
case 2:
break
case 3:
filter = arguments[1]

default:
filter = arguments[1]
print (filter)
}
print (filter)

And this prints out:

4
value
value

Which is exactly what it should print out. Remember the initialization of filter.

Update 2:
This is what you´re trying to do, your other result was always return 4 because that´s the count of arguments. Try the below code instead.

var filter  = String()
func Usage() {
print("Usage: <filter> <input> [output]")
print("System filter paths do not need to be specified.")
return
}

let arguments = ["qwe", "value", "qwe", "asd"]
print(arguments.count)

for i in 0..<arguments.count {
switch i {
case 0:
Usage()
case 1:
Usage()
case 2:
Usage()
case 3:
filter = arguments[1]
default:
filter = arguments[1]
print (filter)
}
}
print (filter)

This prints out:

4
Usage: <filter> <input> [output]
System filter paths do not need to be specified.
Usage: <filter> <input> [output]
System filter paths do not need to be specified.
Usage: <filter> <input> [output]
System filter paths do not need to be specified.
value

Swift: How to access a Switch Statement in a Swift file (error: Statements are not allowed at the top level)?

You are getting this error because you have your switch statement just sitting inside some class or struct (it's not clear where you have this code implemented). To fix your error you will need to put that switch inside a function. Perhaps you could create a function called setTheme, like so:

var theme = UserDefaults.standard.string(forKey: "themes")

var background: UIColor?
var labelColor: UIColor?
var buttonColor: UIColor?

func setTheme() {
//First, check to make sure theme is not nil
guard let theme = self.theme else { return }
switch theme {
case "Red":
background = UIColor(named: "darkRed")
labelColor = UIColor(named: "labelRed")
buttonColor = UIColor(named: "buttonRed")
case "Blue":
background = UIColor(named: "darkBlue")
labelColor = UIColor(named: "labelBlue")
buttonColor = UIColor(named: "buttonBlue")
default:
return
}
}

Another option would be to make your UIColor? attributes computed variables. For example:

var background: UIColor? {
guard let theme = self.theme else { return nil }
switch theme {
case "Red": return UIColor(named: "darkRed")
case "Blue": return UIColor(named: "darkBlue")
default: return nil
}
}

switch and cannot find variable in scope

A pair of braces is called a scope.

In Swift (unlike some other languages) there is a simple but iron rule:

  • A variable declared inside a scope – in your particular case inside the switch statement – is visible in its own scope and on a lower level – like in your second example

  • It's not visible on a higher level outside the scope – like in your first example.

You can even declare size as constant because it's guaranteed to be initialized.

func sizeCheckVar(value: Int) -> String {
let size: String
switch value {
case 0...2: size = "small"
case 3...5: size = "medium"
case 6...10: size = "large"
default: size = "huge"
}
return size
}

However actually you don't need the local variable at all. Just return the values immediately

func sizeCheckVar(value: Int) -> String {
switch value {
case 0...2: return "small"
case 3...5: return "medium"
case 6...10: return "large"
default: return "huge"
}
}

Side note: The colon in a switch statement is also a kind of scope separator otherwise you would get errors about redeclaration of variables in the first example.

Lesser than or greater than in Swift switch statement

Here's one approach. Assuming someVar is an Int or other Comparable, you can optionally assign the operand to a new variable. This lets you scope it however you want using the where keyword:

var someVar = 3

switch someVar {
case let x where x < 0:
print("x is \(x)")
case let x where x == 0:
print("x is \(x)")
case let x where x > 0:
print("x is \(x)")
default:
print("this is impossible")
}

This can be simplified a bit:

switch someVar {
case _ where someVar < 0:
print("someVar is \(someVar)")
case 0:
print("someVar is 0")
case _ where someVar > 0:
print("someVar is \(someVar)")
default:
print("this is impossible")
}

You can also avoid the where keyword entirely with range matching:

switch someVar {
case Int.min..<0:
print("someVar is \(someVar)")
case 0:
print("someVar is 0")
default:
print("someVar is \(someVar)")
}

Using if let syntax in switch statement

If all you want to know is whether it's a B or a C, you can just say case is B and case is C.

If you want to capture and cast down, then say case let b as B and case let c as C.

When I use for as a switch statement's expression, Swift returns an error. How to get around this?

for is a reserved word, if you want to use reserved words as variable or function names you need to escape them with back-ticks.

Try this

switch `for` {

PS. You can improve this function signature by adding a variable name that is different from the label, like this

func synoynms(for word: String) -> [String]? {
switch word {

Now word is the name of your variable, and calls still look like this: synonyms(for: "cheese")

How to set a variable to start at 0 and gain a level through each loop in a nested for loop Swift 2

Define your u variable outside of your first for loop and u += 1 on the end of your outside loop

Check this

var u : Int = 0
placeLoop: for aPlace in place {
print("\(aPlace)")
print(" ")

if aPlace == place[u] {
place[u] = place[++u]
//This is the manual way to achieve what I want but I have 105 records I want to iterate through, there has to be a better way to do this.
//place[u] = var place[u]
//place[1] = place[2]
//place[2] = place[3]
//if aPlace is equal to place0 then 0 = 1, next loop 1 = 2, next loop 2 =3
//you can't ++ a "String which place[with an index] is.
u += 1

I hope this helps you, Regards



Related Topics



Leave a reply



Submit