[英]Unused type parameter in swift
Is there a keyword to place-hold unused type parameters? 是否有关键字来保留未使用的类型参数?
In this example, receiver
does not use T
of MyGen
. 在此实例中,
receiver
不使用T
的MyGen
。 In Java language, it can be written MyGen<?> v
. 用Java语言,可以写成
MyGen<?> v
。 I could not find a counterpart in swift language documents. 我在快速的语言文档中找不到对应的内容。
import Foundation
class MyGen<T: Printable> {
var value: T
init(v: T) {
value = v
}
}
func receiver(v: MyGen<WHAT_COMES_HERE>) {
println(v);
}
let s = MyGen<NSString>(v: "hello")
receiver(s)
I know that giving receiver
a type parameter solves the problem, but it is not welcome because upper bound Printable
is repeated as many as functions and the code has redundant information. 我知道为
receiver
提供类型参数可以解决此问题,但是不欢迎这样做,因为上限Printable
会重复执行与函数一样多的操作,并且代码中包含冗余信息。
// This works, but not welcome
func receiver<T: Printable>(v: MyGen<T>) {
println(v);
}
In Swift, despite it not being used, you have to declare a type parameters. 在Swift中,尽管没有使用它,但您必须声明一个类型参数。 But, you don't need
:Printable
in here, You can use just T
or whatever as you like. 但是,您不需要
:Printable
在此处,您可以仅使用T
或任意使用。
func receiver<A>(v: MyGen<A>) {
println(v)
}
Use :
for the type parameter, only if receiver
requires more specialized MyGet.T
. 仅当
receiver
需要更专业的MyGet.T
类型参数使用:
。 For example: 例如:
class MyGen<T: Printable> {
var value: T
init(v: T) {
value = v
}
}
// `receiver` accepts `MyGen` only if its `T` is a sequence of `Int`
func receiver<A: SequenceType where A.Generator.Element == Int>(v: MyGen<A>) {
println(reduce(v.value, 0, +))
}
let s = MyGen<[Int]>(v: [1,2,3])
receiver(s) // -> 6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.