Is it possible for a Closure (Swift) to capture reference of the instance of the object that executes it?

Asked

Viewed 150 times

0

I am passing a closure for the property of an object, and within the closure would need to make a reference to the instance of the object that will run the closure. Example:

 typealias validator : ()->Bool

      class Field : NSObject {
         var name     : String?
         var validate : validator?
     }

     var primeiroNome       = Field()
      primeiroNome.name     = "Pedro"
      primeiroNome.validate = { ()-Bool

       // self ou uma outra referencia a instancia de primeiroNome
       return self.name != "" ? true : false

     }

    primeiroNome.validate() // Retorna true ou false

The solution I’m using is to use a closure that takes a Field-type instance as a parameter in this way:

typealias validator : (_ instance : Field)->Bool

  class Field : NSObject {
     var name     : String?
     var validate : validator?  }

 var primeiroNome      = Field()  
 primeiroNome.name     = "Pedro"  
 primeiroNome.validate = { (instance)-Bool -> in

   // self ou uma outra referencia a instancia de primeiroNome    
   return instance.name != "" ? true : false

 }

 primeiroNome.validate(primeiroNome) // Retorna true ou false

The alternative I found works, but I would really like to be able to run the closure without having to pass the instance as a parameter.

2 answers

1


Not. Why?

Clousures sane Reference Types. That means when you declare a clousure a variable, you are declaring its type, not its value. The contents of this clousure yes will be the value of your variable.

Example:

var exemplo : () -> Bool = { return true }

We can read the line above like this:

"The'example 'variable is a clousure of the type () -> Bool with positive boolean value"

To "capture the instance reference of the object that executes it", you will need to do this across of the instance of clousure, that is, inside the block.

Tip off-topic: Use a capture list to change the reference Strong of your self for Weak or unowned. This will make you not create Strong Reference Cycles.

More about clousures:

Clousures Are Reference Types - The Swift Programming Language (https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html#//apple_ref/doc/uid/TP40014097-CH11-ID104):

1

It seems that the code that you have pasted is not complete. But by what you have written, the.

class Field {
    var name: String?
    var validate: (() -> Bool)?
}

class MyClass {
    var field: Field {
        let myField = Field()
        myField.validate = { self.field.name != nil }
        return myField
    }

    func validateField(){
        field.validate?()
    }
}

MyClass().validateField()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.