2015-02-06 47 views
0

是否有關鍵字放置 - 保留未使用的類型參數?swift中未使用的類型參數

在此示例中,receiver未使用MyGenT。 在Java語言中,它可以寫成MyGen<?> v。 我無法在swift語言文檔中找到對應的對象。

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); 
} 

回答

0

在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 
相關問題