Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unary operator '--' cannot be applied to an operand of type '@lvalue Int?' (aka '@lvalue Optional<Int>') [duplicate]

Tags:

swift

swift3

I just updated my app's code to the latest version of Swift and I have this function:

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
                }
            }
        }
    }

However I am getting an error message at the following line:

labelView.text = days[(weekday--)!]

Where Xcode is giving me the following error:

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

I tried searching online for answers but I still couldn't find anything that would help me fix this error.

I was also curious what the error message exactly means by type @lvalue Int (aka '@lvalue Optional<Int>')? I have never seen this data type before and don't know how to solve the problem accordingly.

Thanks in advance.

like image 326
Ahad Sheriff Avatar asked Feb 02 '17 21:02

Ahad Sheriff


1 Answers

Answer is very simple. ++ and -- was removed from Swift 3. But += and -= remained

About Optional<Int> this is longer version for Int? definition. In Swift Optional defined as public enum Optional<Wrapped> : ExpressibleByNilLiteral

like image 72
oroom Avatar answered Dec 24 '22 11:12

oroom