【问题标题】:Generic function conforming to custom protocol - Swift符合自定义协议的通用函数 - Swift
【发布时间】:2018-08-10 09:10:51
【问题描述】:

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

下面是我在操场上的代码。

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)。

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

【问题讨论】:

  • custom(with:) 返回Void(又名())。
  • @Cristik 我应该在我的代码中更改什么
  • 不确定。取决于你想完成什么。
  • 不清楚您要完成什么;您是否尝试使用initFunctionsAvailable 来实现某种工厂模式? custom 在您的示例中应该返回什么? model1的实例?
  • 是 model1 的一个实例。它应该根据我的传入参数而有所不同

标签: ios swift generics


【解决方案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
} 

【讨论】:

    【解决方案2】:

    这也可以。

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多