在Swift中输入带有模板的别名声明 [英] Type Alias Declaration with templates in Swift
问题描述
如何避免在 f0
, f1
,... f10
?
class SomeClass< T:UnsignedInteger> (序列:S)其中S.Iterator.Element == T {}
func f1< S:序列>(序列:S)其中S .Iterator.Element == T {}
......
func f10< S:Sequence>(sequence:S)其中S.Iterator.Element == T {}
}
如何声明如下:
< pre $ typealias S = Sequence其中S.Iterator.Element == T
func f0(sequence:S){}
func f1(sequence: S){}
......
func f10(sequence:S){}
?
我不确定您是否可以完全按照您的要求进行操作。 typealias是一个可以代替现有类型的符号,它不是一个限制模式。
你可以修改函数类型到类声明的类型通过在类定义中添加一个额外的通用placehoder类型(S):
class SomeClass0< T:UnsignedInteger,S:Sequence>其中S.Iterator.Element == T {
func f0(sequence:S){}
func f1(sequence:S){}
}
但是这意味着引用该类型非常难看,除非您可以从init中推断类型等。
let instance0 = SomeClass0< UInt,[UInt]>()
您仍然可以使用占位符类型在类级别修复序列类型,但省略了UnsignedInteger占位符,具体取决于您使用它的方式:
class SomeClass1< S:Sequence>其中S.Iterator.Element:UnsignedInteger {
typealias T = S.Iterator.Element
func f0(sequence:S){}
func f1(sequence :S){}
func f99(number:T){}
}
let instance1 = SomeClass1< [UInt]>()
How to avoid redundant declaration of restriction in functions f0
, f1
, ... f10
?
class SomeClass<T: UnsignedInteger> {
func f0<S: Sequence>(sequence: S) where S.Iterator.Element == T { }
func f1<S: Sequence>(sequence: S) where S.Iterator.Element == T { }
......
func f10<S: Sequence>(sequence: S) where S.Iterator.Element == T { }
}
How to declare something like this:
typealias S = Sequence where S.Iterator.Element == T
func f0(sequence: S) { }
func f1(sequence: S) { }
......
func f10(sequence: S) { }
?
I'm not sure if you can do exactly what you are asking. A typealias is a symbol that can be used in place of an existing type, it is not a restriction pattern.
You could fix the function types to that of the class declaration by adding an additional generic placehoder type (S) to the class defintion:
class SomeClass0<T: UnsignedInteger, S: Sequence> where S.Iterator.Element == T {
func f0(sequence: S) { }
func f1(sequence: S) { }
}
But that means that referencing the type is pretty ugly, unless you can infer types from an init etc..
let instance0 = SomeClass0<UInt, [UInt]>()
You could still fix the sequence type at the class level with the placeholder type, but leave out the UnsignedInteger placeholder, depending on exactly how you are using it:
class SomeClass1<S: Sequence> where S.Iterator.Element: UnsignedInteger {
typealias T = S.Iterator.Element
func f0(sequence: S) { }
func f1(sequence: S) { }
func f99(number: T) {}
}
let instance1 = SomeClass1<[UInt]>()
这篇关于在Swift中输入带有模板的别名声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!