![](/img/trans.png)
[英]Xcode 8 / Swift 3: “Expression of type UIViewController? is unused” warning
[英]Unused type parameter in swift
是否有关键字来保留未使用的类型参数?
在此实例中, receiver
不使用T
的MyGen
。 用Java语言,可以写成MyGen<?> v
。 我在快速的语言文档中找不到对应的内容。
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)
我知道为receiver
提供类型参数可以解决此问题,但是不欢迎这样做,因为上限Printable
会重复执行与函数一样多的操作,并且代码中包含冗余信息。
// This works, but not welcome
func receiver<T: Printable>(v: MyGen<T>) {
println(v);
}
在Swift中,尽管没有使用它,但您必须声明一个类型参数。 但是,您不需要:Printable
在此处,您可以仅使用T
或任意使用。
func receiver<A>(v: MyGen<A>) {
println(v)
}
仅当receiver
需要更专业的MyGet.T
类型参数使用:
。 例如:
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.