gpt4 book ai didi

ios - 符合自定义协议(protocol)的通用函数 - Swift

转载 作者:可可西里 更新时间:2023-11-01 01:09:18 28 4
gpt4 key购买 nike

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

下面是我在 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)

我收到错误

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

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

最佳答案

问题出在这里:

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
}

关于ios - 符合自定义协议(protocol)的通用函数 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49064283/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com