typealias泛型函数

时间:2014-09-21 21:15:12

标签: function generics swift

作为一项学习练习,我试图编写一个小型的功能库。我的库中的许多函数都需要传入一个函数。我想" typealias"这个函数使我的库的用户必须传入一个具有特定签名的函数。

我试过这个:

typealias Callback = Result<AnyObject> -> ()

这种作品,但我希望AnyObject部分是任何。不是AnyObject,因为它实际上是某种真实类型(?)。我的Result枚举基于此article有关Swift中的错误处理。它是一个通用枚举,所以我希望在我的函数签名中反映出来。

如果我删除<AnyObject>部分,我会收到错误消息:

  

参考通用类型&#39;结果&#39;需要&lt; ...&gt;

中的参数

如果我只是Result<T>我收到错误:

  

使用未申报的类型&#39; T&#39;

据我所知,它不可能使用typealias generics。那么......围绕着这个吗?

TLDR;

我有一堆函数,我希望将特定签名的函数作为参数,在我的情况下:

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

我该怎么强迫这个?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

这里我将介绍swift 2.0中 typealias 的示例,其中展示了如何在协议定义中使用 typealias :我希望这有助于您了解swift 2.0中的typealias

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

答案 2 :(得分:0)

Swift 4.1支持通用类型别名。您可以使用此功能为具有通用参数的函数提供名称。

您可能必须使用以下声明:

typealias Callback<T> = (Result<T>) -> ()