我正在尝试编写一些逻辑来简化我的代码。变量的值 (pointpb
) 根据不同的输入而改变,并且根据该变量的值,将执行 if
语句。
我最初在 if
语句中声明了这个变量,但一旦我意识到它不能在该语句之外使用,我很快就改变了它。我已经使用了通常的资源。 Google、YouTube 和浏览 Apple 的文档,在代码的不同范围内声明变量等,但似乎无法找到这是为什么。
class MapViewController: UIViewController, MKMapViewDelegate {
var pointpb = 0
//add icon push button action/draw select enable
@IBAction func Addpointpb(_ sender: UIButton)
{
pointpb = 1
Iconselected.textColor = UIColor.blue
self.Iconselected.text = "Select One"
self.Circleselect.isHidden = false
self.Lineselect.isHidden = false
self.Pointselelct.isHidden = false
}
//point selected
@IBAction func Pointselect(_ sender: UIButton)
{
pointpb = 2
self.Pointselelct.isHidden = true
self.Circleselect.isHidden = true
self.Lineselect.isHidden = true
self.Addpointpb.isHidden = true
self.Pointcancel.isHidden = false
self.Iconselected.text = "Point"
}
//line selected
@IBAction func Lineselect(_ sender: UIButton)
{
pointpb = 3
self.Pointselelct.isHidden = true
self.Circleselect.isHidden = true
self.Lineselect.isHidden = true
self.Addpointpb.isHidden = true
self.Pointcancel.isHidden = false
self.Iconselected.text = "Line"
}
//circle selected
@IBAction func Circleselect(_ sender: UIButton)
{
pointpb = 4
self.Pointselelct.isHidden = true
self.Circleselect.isHidden = true
self.Lineselect.isHidden = true
self.Addpointpb.isHidden = true
self.Pointcancel.isHidden = false
self.Iconselected.text = "Circle"
}
}
//==================================================================
//preferred code for me to use
//point selected
@IBAction func Pointselect(_ sender: UIButton)
{
pointpb = 2
self.Iconselected.text = "Point"
}
//line selected
@IBAction func Lineselect(_ sender: UIButton)
{
pointpb = 3
self.Iconselected.text = "Line"
}
//circle selected
@IBAction func Circleselect(_ sender: UIButton)
{
pointpb = 4
self.Iconselected.text = "Circle"
}
//if statement
if pointpb == 2, pointpb == 3, pointpb == 4
{
self.Pointselelct.isHidden = true
self.Circleselect.isHidden = true
self.Lineselect.isHidden = true
self.Addpointpb.isHidden = true
self.Pointcancel.isHidden = false
}
如您所见,最后三个函数的 UIButton
输入基本上做同样的事情。理想情况下,我想使用底部的代码部分。但是,如前所述,该变量不再被识别,我收到指向该 if
语句的“预期声明”错误。我觉得这是一件非常明显的事情,但显然我很愚蠢。
最佳答案
您编写 if 语句的方式更接近一次声明多个变量的语法,因此 Xcode 将其称为“预期声明”
编写 if 子句的正确方法是
if (pointpb == 2 || pointpb == 3 || pointpb == 4)
查看 Swift basics重温语法
另外,作为一个提示,您可以使用 if [2, 3, 4].contains(pointpb)
关于swift - 无法识别 if 语句条件中使用的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56780992/