Search code examples
iosswiftclosuresvariable-types

Why Same Closure type does not get assigned


class ParentClass<T>
{
    var success : ((T)->Void)?
}

extension ParentClass
{
   func success<T>(success: ((T) -> Void)?) -> ParentClass where T : Codable
   {
        self.success = success
        return self
    }
}

here I just tried to assign the parameter value to parent class variable but it throw this error Cannot assign value of type '((T) -> Void)?' to type '((T) -> Void)?'

Also when I go for suggestion prompt, again again it gives me the same error.


Solution

  • Because the Generic type you used in the class (and for the variable) definition is NOT same with the Generic you defined in the function signature. You should make sure both are same:

    class ParentClass<T> {    
        var success : ((T)->Void)?
    }
    
    extension ParentClass {
       func success(success: ((T) -> Void)?) -> ParentClass {
            self.success = success
            return self
        }
    }
    

    And if you want it to be codable:

    class ParentClass<T: Codable> { ,,, }
    

    Or in the extension:

    extension ParentClass where T: Codable { ,,, }