Saranjith
Saranjith

Reputation: 11547

Generic function conforming to custom protocol - Swift

I want to make a function which accepts the desired return type as parameter and which should conform to my custom protocol.

Below is my code from playground.

protocol InitFunctionsAvailable {
    func custom(with: Array<Int>)
}

class model1: InitFunctionsAvailable {
    var array: Array<Int>!

    func custom(with: Array<Int>) {
        array = with
    }

}

func call<T: InitFunctionsAvailable>(someObject: T) -> T {

    return someObject.custom(with: []) as! T
}


let model = call(someObject: model1())

print(model.array)

Im getting error

Could not cast value of type '()' (0x1167e36b0) to '__lldb_expr_76.model1' (0x116262430).

What I need is the function should return the model depending on parameters.

Upvotes: 2

Views: 235

Answers (2)

brduca
brduca

Reputation: 3623

That does the job too.

import Foundation

protocol InitFunctionsAvailable
{
    func custom(with: Array<Int>) -> InitFunctionsAvailable
}

class model1: InitFunctionsAvailable
{
    var array: Array<Int>!

    func custom(with: Array<Int>) -> InitFunctionsAvailable
    {
        array = with
        return self
    }
}

func call<T: InitFunctionsAvailable>(someObject: T) -> T
{
    return someObject.custom(with: []) as! T
}


let model = call(someObject: model1())

print(model.array)

Upvotes: 1

Milan Nos&#225;ľ
Milan Nos&#225;ľ

Reputation: 19737

The problem is here:

return someObject.custom(with: []) as! T

someObject.custom(with: []) has no return value, thus it "returns" Void (or () if you want), but you are trying to cast it to T, which in you example is model1 instance. You cannot cast Void to model1.

You can in your case simplu fix it by changing call method from:

func call<T: InitFunctionsAvailable>(someObject: T) -> T {

    return someObject.custom(with: []) as! T
}

to:

func call<T: InitFunctionsAvailable>(someObject: T) -> T {
    // perform action on it
    someObject.custom(with: [])
    // and then return it
    return someObject
} 

Upvotes: 1

Related Questions