一元运算符' - '不能应用于'@lvalue Int?'类型的操作数.(又名'@lvalue Optional <Int>')

Aha*_*iff 19 swift swift3

我刚刚将我的应用程序代码更新到最新版本的Swift,我有这个功能:

func setupGraphDisplay() {

        //Use 7 days for graph - can use any number,
        //but labels and sample data are set up for 7 days
        //let noOfDays:Int = 7

        //1 - replace last day with today's actual data
        graphView.graphPoints[graphView.graphPoints.count-1] = counterView.counter

        //2 - indicate that the graph needs to be redrawn
        graphView.setNeedsDisplay()

        maxLabel.text = "\((graphView.graphPoints).max()!)"
        print((graphView.graphPoints).max()!)

        //3 - calculate average from graphPoints
        let average = graphView.graphPoints.reduce(0, +)
            / graphView.graphPoints.count
        averageWaterDrunk.text = "\(average)"

        //set up labels
        //day of week labels are set up in storyboard with tags
        //today is last day of the array need to go backwards

        //4 - get today's day number
        //let dateFormatter = NSDateFormatter()
        let calendar = Calendar.current
        let componentOptions:NSCalendar.Unit = .weekday
        let components = (calendar as NSCalendar).components(componentOptions,
            from: Date())
        var weekday = components.weekday

        let days = ["S", "S", "M", "T", "W", "T", "F"]

        //5 - set up the day name labels with correct day
        for i in (1...days.count).reversed() {
            if let labelView = graphView.viewWithTag(i) as? UILabel {
                if weekday == 7 {
                    weekday = 0
                }
                labelView.text = days[(weekday--)!]
                if weekday! < 0 {
                    weekday = days.count - 1
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下行的错误消息:

labelView.text = days[(weekday--)!]
Run Code Online (Sandbox Code Playgroud)

Xcode给我以下错误:

Unary operator '--' cannot be applied to an operand of type '@lvalue Int?' (aka '@lvalue Optional<Int>')
Run Code Online (Sandbox Code Playgroud)

我尝试在线搜索答案,但我仍然找不到任何可以帮助我解决此错误的内容.

我也很好奇错误信息究竟是什么意思@lvalue Int (aka '@lvalue Optional<Int>')?我以前从未见过这种数据类型,也不知道如何解决问题.

提前致谢.

Dzm*_*vak 42

答案很简单.++和 - 从Swift 3中删除了.但+ =和 - =仍然存在

关于Optional<Int>这是Int?定义的更长版本.在Swift Optional中定义为 public enum Optional<Wrapped> : ExpressibleByNilLiteral

  • 这是另一个可怕的错误消息.如果运算符不存在,为什么它会抱怨它们应用的类型(这意味着它们确实存在于某些类型中)而不仅仅是说明运算符无效? (15认同)