I'm passing a closure to an object's property, and within the closure I'd need to reference the instance of the object that will execute 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 gets an instance of type Field as parameter like this:
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.