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.