Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to define a variable in a Swift if statement?

Is it possible to define a variable in a Swift if statement and then use it outside of the statement?

    var cellWidth = requiredWidth
    if notification.type == "vote"{
        var cellWidth = maxWidth - 80
        println("cellWidth is \(cellWidth)")
        println("maxWidth is \(maxWidth)")
    }
    println("cellWidth is \(cellWidth)")

I could just duplicate the code that uses cellWidth into the if statement, but that seems inefficient. Is there a better approach to handling conditional variables in Swift?

like image 406
Oakland510 Avatar asked Aug 19 '15 17:08

Oakland510


2 Answers

No you can not. The if statement defines a local scope, so whatever variable you define inside its scope, won't be accessible outside of it.

You have a few options

var cellWidth = requiredWidth
if notification.type == "vote"{
    cellWidth = maxWidth - 80
    println("cellWidth is \(cellWidth)")
    println("maxWidth is \(maxWidth)")
}
println("cellWidth is \(cellWidth)")

or (better IMHO) without using variable, but only constants

func widthForCell(_ maxWidth: CGFloat, _ requiredWidth: CGFloat, _ notification: Notification) -> CGFloat {
  switch notification.type {
    case "vote": return maxWidth - 80
    default: return requiredWidth
  }
}
let cellWidth = widthForCell(maxWidth, requiredWidth, notification)
println("cellWidth is \(cellWidth)")
like image 63
Gabriele Petronella Avatar answered Dec 08 '22 00:12

Gabriele Petronella


In your code, you are actually creating two separate variables, both called cellWidth. They have different scopes: inside the if statement, the cellWidth created in that scope is prioritised, as it has the deepest scope; outside the if statement, the inner cellWidth is not visible, as it cannot access that scope. So with the code above, you will find that the last println statement will always print a value equal to requiredWidth, even when the if statement is evaluated.

What you actually want to do is just use modify the existing cellWidth variable inside the if statement:

var cellWidth = requiredWidth
if notification.type == "vote"{
    cellWidth = maxWidth - 80
    println("cellWidth is \(cellWidth)")
    println("maxWidth is \(maxWidth)")
}
println("cellWidth is \(cellWidth)")

Of course, if your code is actually as simple as shown in the question above, you can simply use:

let cellWidth = notificationType == "vote" ? maxWidth - 80 : requiredWidth
like image 29
Stuart Avatar answered Dec 08 '22 00:12

Stuart