简体   繁体   中英

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.

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
} 

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM