Jonathan Dunlap
Jonathan Dunlap

Reputation: 2631

Struct passing self causes: self subtype of @lvaue error

Best way I can describe the situation is just to show an example:

struct One {
  func setup(inout t:Two) {
    // inout is important to not copy the struct in
  } 
}

struct Two {
  func getOne() -> One {
    var o = One()
    o.setup(&self) // Two is not subtype of '@lvalue $T5'
    return o
  }
}

Why is this happening and how can I get past it?

Upvotes: 0

Views: 280

Answers (1)

Bryan Chen
Bryan Chen

Reputation: 46608

you need to add mutating keyword to the method. otherwise method in struct are default to immutable, which means you cannot modify self in the method. and pass self to another method takes inout keyword implicitly saying you are going to modify it.

struct Two {
  mutating func getOne() -> One {
    var o = One()
    o.setup(&self) // Two is not subtype of '@lvalue $T5'
    return o
  }
}

Upvotes: 1

Related Questions