![](/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.