Ios 符合自定义协议的通用功能-Swift
我想做一个函数,它接受所需的返回类型作为参数,并且应该符合我的自定义协议 下面是我在操场上的代码Ios 符合自定义协议的通用功能-Swift,ios,swift,generics,Ios,Swift,Generics,我想做一个函数,它接受所需的返回类型作为参数,并且应该符合我的自定义协议 下面是我在操场上的代码 protocol InitFunctionsAvailable { func custom(with: Array<Int>) } class model1: InitFunctionsAvailable { var array: Array<Int>! func custom(with: Array<Int>) { a
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)
协议初始化功能可用{
func自定义(带:数组)
}
类model1:InitFunctionsAvailable{
变量数组:数组!
func自定义(带:数组){
数组=带
}
}
func调用(someObject:T)->T{
将someObject.custom(带:[])返回为!T
}
让model=call(someObject:model1())
打印(model.array)
我收到错误信息
无法将类型为“()”(0x1167e36b0)的值强制转换为
'lldb_expr_76.model1'(0x116262430)
我需要的是函数根据参数返回模型。问题在于:
return someObject.custom(with: []) as! T
someObject.custom(with:[])
没有返回值,因此它“返回”Void
(或者()
,如果需要的话),但您试图将其强制转换为T
,在您的示例中,它是model1
实例。您不能将Void
强制转换为model1
在您的情况下,可以通过将call
method从以下位置更改来修复它:
func call<T: InitFunctionsAvailable>(someObject: T) -> T {
return someObject.custom(with: []) as! T
}
func调用(someObject:T)->T{
将someObject.custom(带:[])返回为!T
}
致:
func调用(someObject:T)->T{
//对其执行操作
someObject.custom(使用:[])
//然后把它还给我
返回某物
}
这也能完成任务
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)
<代码>导入基础
协议初始化函数可用
{
func自定义(带:数组)->InitFunctionsAvailable
}
类model1:InitFunctionsAvailable
{
变量数组:数组!
func自定义(带:数组)->InitFunctionsAvailable
{
数组=带
回归自我
}
}
func调用(someObject:T)->T
{
将someObject.custom(带:[])返回为!T
}
让model=call(someObject:model1())
打印(model.array)
自定义(带:)
返回无效
(又名()
)。@Cristik我应该在代码中更改什么不确定。这取决于你想完成什么。不清楚你想完成什么;您是否试图使用initFunctionsAvailable
实现某种工厂模式?在您的示例中,custom
应该返回什么?model1的实例
?是model1的实例。它应该根据传入参数而变化
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)