是否可以在Swift if语句中定义变量? [英] Is it possible to define a variable in a Swift if statement?

查看:354
本文介绍了是否可以在Swift if语句中定义变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在Swift if语句中定义变量,然后在语句之外使用它?

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)")

我可以将使用cellWidth的代码复制到if语句中,但是似乎效率低下。有没有更好的方法来处理Swift中的条件变量?

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?

推荐答案

不,你不能。 if 语句定义了一个本地范围,因此无论您在其范围内定义什么变量,都无法在其外部访问。

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.

你有几个选择

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)")

这篇关于是否可以在Swift if语句中定义变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆