user3903647
user3903647

Reputation: 95

Swift: error passing self as inout parameter parameter

I have this case:

class classA{
  var objB : classB;

   init(){
      objB = classB(&self) //ERROR!
  }
}

class classB{
 var _objA : classA

  init(inout objA : classA){
      _objA = objA;
  }
}

I receive the message: 'classA' is not a subtype of '@lvalue $T3'

Upvotes: 3

Views: 2643

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727077

The error is misleading, but your program should not compile: it does not make sense to pass self as an in-out parameter. Swift book is clear about what can be passed as inout:

You can only pass a variable as the argument for an in-out parameter.

This makes perfect sense: imagine what would happen if your function assigned a new value to its objA parameter. Since it corresponds to self in the caller, the caller object would need to be replaced with a new one, which does not have a clear semantics.

You can fix this by defining a temporary variable for self, like this:

var temp = self;
objB = classB(&temp)

Upvotes: 10

Related Questions