符合自定义协议的通用函数 - Swift

问题描述 投票:2回答:2

我想创建一个函数,它接受所需的返回类型作为参数,并且应该符合我的自定义协议。

以下是我在游乐场的代码。

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)

我得到错误

无法将类型'()'(0x1167e36b0)的值转换为'__lldb_expr_76.model1'(0x116262430)。

我需要的是函数应该根据参数返回模型。

ios swift generics
2个回答
1
投票

问题出在这里:

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

someObject.custom(with: [])没有返回值,因此它“返回”Void(或(),如果你想),但你试图把它投射到T,在你的例子中是model1实例。你不能把Void施加到model1

您可以在您的情况下通过更改call方法来修复它:

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

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

至:

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

1
投票

这也完成了这项工作。

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)
© www.soinside.com 2019 - 2024. All rights reserved.