Bevin Patel
Bevin Patel

Reputation: 302

Cannot assign value of type '((T) -> Void)?' to type '((T) -> Void)?'

import Foundation

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


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

I am trying to store generic closure in to variable for later use but compiler throwing an error."Cannot assign value of type '((T) -> Void)?' to type '((T) -> Void)?'"

Upvotes: 0

Views: 190

Answers (1)

Alexander
Alexander

Reputation: 63167

You've introduced a local generic variable T, which is shadowing the (unrelated) generic variable T of ParentClass.

import Foundation

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


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

However, it doesn't really make sense that your success function is an instance method. It should be an initializer, or a static method instead.

Upvotes: 5

Related Questions