我正在尝试编写一些逻辑来简化我的代码。变量的值(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
语句的“预期声明”错误。我觉得这很愚蠢,但显然我很愚蠢。
答案 0 :(得分:0)
您编写if语句的方式更接近于一次声明多个变量的语法,因此Xcode称其为“预期声明”
编写if子句的正确方法是
if (pointpb == 2 || pointpb == 3 || pointpb == 4)
签出Swift basics来复习语法
作为一个提示,您可以使用if [2, 3, 4].contains(pointpb)