2014-09-21 38 views
2

作爲一種學習練習,我試圖編寫一個小函數庫。我的庫中的許多函數都需要傳入一個函數。我希望「函數式」這個函數,以便我的庫的用戶必須傳遞一個具有特定簽名的函數。typealias通用函數

我已經試過這樣:

typealias Callback = Result<AnyObject> ->()

這類作品,但我想AnyObject部分是任何。不是特別的AnyObject,因爲這實際上是某種真實類型(?)。我的Result枚舉我基於這個article關於Swift中的錯誤處理。這是一個泛型的枚舉,所以這就是我想要反映在我的函數簽名中的東西。

如果我刪除<AnyObject>部分,我得到一個錯誤說:

Reference to generic type 'Result' requires arguments in <...>

如果我只是爲了Result<T>我得到的錯誤:

Use of undeclared type 'T'

至於我的理解是它的不可能使用泛型。所以......在這附近呢?

TLDR;

我有一堆的,我想採取特定簽名的函數作爲參數的功能,在我的情況:

(result: Result<T>) ->()

如何強制呢?

+0

作爲@natecook筆記,這是目前不可能,但我們也只是討論了幾乎同樣的事情在這裏:http://stackoverflow.com/questions/25909856/how-do-i- generify-a-closure-type-alias-in-swift/25912041#25912041 – 2014-09-22 06:08:26

回答

1

正如你提到的,有沒有辦法有一個typealias是通用(language reference),但你仍然可以包括在函數定義你的方法簽名,它只是有點亂:

enum Result<T> { 
    case Success(T) 
    case Failure 
} 

func printResult<T>(result: Result<T>) { 
    switch result { 
    case .Success(let value): 
     println(value) 
    case .Failure: 
     println("failure") 
    } 
} 

func doSomething<T>(value: T?, f: (Result<T>) ->()) { 
    if value != nil { 
     f(Result<T>.Success(value!)) 
    } else { 
     f(Result<T>.Failure) 
    } 
} 

doSomething(21, printResult) 
// 21 

// can't do this, since type inference for the generic 
// Result<T> doesn't work on just `nil`: 
// doSomething(nil, printResult) 

let noString: String? = nil 
doSomething(noString, printResult) // now calling as doSomething<String> 
// failure 
+0

謝謝,但你誤會了。我不清楚,我會更新我的問題。但基本上我只是想強制該函數的_signature_。我希望我的庫的用戶能夠使用_any_函數體傳遞_any_函數。 – simme 2014-09-22 05:49:40

+0

'doSomething'函數就是這樣 - 它的第二個參數將帶有任何具有一個'Result '參數並返回'Void'的函數。 'printResult'只是一個例子。 – 2014-09-22 05:52:43

+0

對不起,誤解了你的問題。我已經知道了。如果可能的話,我想要做的就是採用'f:(結果) - >()'並將其設爲'f:回調函數'以避免必須反覆寫第一個!抱歉不清楚。 – simme 2014-09-22 05:55:13

0

我在這裏例如呈現在SWIFT 2.0typealias展示瞭如何使用typealias在協議定義:我希望這可以幫助你瞭解typealias在SWIFT 2.0

protocol NumaricType { 

typealias elementType 

func plus(lhs : elementType, _ rhs : elementType) -> elementType 

func minus(lhs : elementType, _ rhs : elementType) -> elementType 
} 


struct Arthamatic :NumaricType { 

func addMethod(element1 :Int, element2 :Int) -> Int { 
    return plus(element1, element2) 
} 
func minusMethod(ele1 :Int, ele2 :Int) -> Int { 
    return minus(ele1, ele2) 
} 

typealias elementType = Int 

func plus(lhs: elementType, _ rhs: elementType) -> elementType { 
    return lhs + rhs 
} 
func minus(lhs: elementType, _ rhs: elementType) -> elementType { 
    return lhs - rhs 
} 
} 

輸出:

 let obj = Arthamatic().addMethod(34, element2: 45) // 79