Codey
Codey

Reputation: 1233

Cannot assign to "" in "self" - Working with Tuples in Swift

I have to classes: FirstViewController and PlanGenerator.

PlanGenerator has a method called getPlanForIndex (day:Int) -> ([PlanElement], [PlanElement])?. It is returning two different Arrays, both containing Object of Plan Element.

getPlanForIndex (day:Int) -> ([PlanElement], [PlanElement])? {

    // Do some work and fill arrays
    return (firstArray, secondArray)
}

In the FirstViewController I've created two Properties:

let plan:[PlanElement] = [PlanElement]()
let planGen:PlanGenerator = PlanGenerator()

FirstViewControllerhas a method called:

func prepareView () {

    plan = planGen.getPlanForIndex(dayIndex)    
}

But when I want to call this, I get the error message: Cannot assign to 'plan' in 'self'

Upvotes: 1

Views: 1307

Answers (1)

rickster
rickster

Reputation: 126127

First, your plan member is a constant (declared with let), and you're assigning to it outside of init. If you want to assign to it after initialization, it needs to be declared with var.

Also, your getPlanForIndex returns a tuple, and you're assigning it to a member of singular (not tuple) type. If you want to assign one part of a tuple only, do it like this:

    (plan, _) = planGen.getPlanForIndex(dayIndex)    

That assigns a tuple to a tuple, satisfying the compiler, but discards the second element.

If you instead want plan to be a tuple, you'll have to declare and initialize it as such. Looks from the comments like you figured out a way to do that, but here's a way with minimal typing (in either sense of the word):

var plan: ([PlanElement], [PlanElement]) = ([], [])

(Once you've declared the type of array, [] is understood to be an empty array of that type. Just var plan = ([], []) leaves the type ambiguous.)

Upvotes: 4

Related Questions