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

时间:2018-03-02 07:08:24

标签: ios swift generics

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

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

If WaveData IsNot Nothing Then
     WaveData.Dispose()
End If
If WavePlayOut IsNot Nothing Then
     WavePlayOut.Stop()
     WavePlayOut.Dispose()
End If

我收到错误

  

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

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

2 个答案:

答案 0 :(得分: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 :(得分: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)