类型约束中的多个协议 [英] More than one protocol in a type constraint

查看:90
本文介绍了类型约束中的多个协议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class MyCustomClass< T:Equatable> 

我想使用泛型类和类型约束。 {
var a:Array< T>
init(){
a = Array< T>()
}
}

这很好。但是,如果我想使用第二个协议f.e,会发生什么。

  class MyCustomClass< T:Equatable,IndexableBase> {
var a:Array< T>
init(){
a = Array< T>()
}
}

它表示初始化器失败,因为我必须使用2而不是1个参数。我不明白。

解决方案

您可以使用此解决方法

  class MyCustomClass< T:Equatable where T:IndexableBase> {
var a:Array< T>
init(){
a = Array< T>()
}
}


I want to use a generic typed class and a type constraint:

class MyCustomClass<T : Equatable> {
  var a: Array<T>
  init() {
    a = Array<T>()
  }
}

That works fine. But what happens if I want to use a second protocol, f.e.

class MyCustomClass<T : Equatable, IndexableBase> {
  var a: Array<T>
  init() {
    a = Array<T>()
  }
}

It says that the initializer fails because I have to use 2 instead of 1 argument. That I don't understand.

解决方案

you can use this workaround

class MyCustomClass<T: Equatable where T: IndexableBase > {
    var a: Array<T>
    init() {
        a = Array<T>()
    }
}

这篇关于类型约束中的多个协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆