1
protocol LOL {
    var foo: ((_ lol: String) -> Bool)? { get set }
}

class LMAO: LOL {
    internal var foo: ((String) -> Bool)? = { (_ lol: String) in
        self.rofl()
        return true
    }

    func rofl() {}
}

Why is self unresolved in the internal foo variable?

What am I doing wrong here?

user1563544
  • 379
  • 3
  • 17
  • 3
    This is the same problem as in [How to initialize properties that depend on each other](http://stackoverflow.com/questions/25854300/how-to-initialize-properties-that-depend-on-each-other). Making the `foo` property `lazy` is one possible solution. – Martin R Mar 25 '17 at 11:44

1 Answers1

0

The closure you are assigning to foo is independent of your LMAO class so it has no "self".

if you want to initialize your foo variable with code from the current instance's self, you need to use lazy initialization. You will also need to link to the current instance somehow (a plain closure will not do it ).

the easiest way would probably be to add a defaultFoo function to your class and assign it as the initial value:

class LMAO: LOL 
{
  lazy var foo: ((String) -> Bool)? = self.defaultFoo

  func defaultFoo (_ lol: String) -> Bool
  {
    self.rofl()
    return true
  }

  func rofl() {}
}

At this point you probably don't need foo to be an optional, but that's up to you.

Alain T.
  • 40,517
  • 4
  • 31
  • 51
  • Using "a plain closure" will work, you don't need a method. – Hamish Mar 25 '17 at 19:51
  • I stand corrected. A plain closure does indeed work. I wasn't expecting that but since it's part of the class's declaration I guess the compiler ties it to the object and thus has a "self" to work with. – Alain T. Mar 25 '17 at 20:14