Swift中的通用类型别名

69
在 Haskell 中,你可以这样做:
type Parser a = String -> [(a, String)]

我尝试在Swift中制作类似的东西。 到目前为止,我已经写了这些代码,但没有成功。

typealias Parser<A> = String -> [(A, String)]
typealias Parser a = String -> [(a, String)]
typealias Parser = String -> [(A, String)]

那么这在 Swift 中是不是根本不可能实现?如果不可能,是否有其他方法来实现这种行为?

更新:看起来泛型 typealias 现在在 Swift 3 中得到了支持。https://github.com/apple/swift/blob/master/CHANGELOG.md

4个回答

75

用法:> func parse<A>(stringToParse: String, parser: Parser) - Calin Drule

37

typealias 目前无法与泛型一起使用。您最好的选择可能是将解析器函数包装在一个结构体中。

struct Parser<A> {
    let f: String -> [(A, String)]
}

当创建解析器时,您可以使用尾随闭包语法,例如:

let parser = Parser<Character> { string in return [head(string), tail(string)] }

@mustafa 你好,请问你能告诉我哪一部分表示装箱吗?你不是指Java中的装箱,对吧?此外,我对[head(string)...tail(string)]有些困惑。谢谢。 - Unheilig
1
@Unheilig Boxing 指将一种类型包装在另一种类型中,以利用仅在外部类型中找到的功能。您可能熟悉 Objective-C 中的这个概念,其中诸如整数之类的基元无法传递到 NSArray 中,而必须在 NSNumber 中“打包”,例如 @(1234)。头/尾的事情不是特定于 Swift 的,而是将数组拆分为第一个项目(头)和其余项目(尾)的常见模式。请参见 http://chris.eidhof.nl/posts/swift-tricks.html - clozach
@clozach,谢谢您的解释。我会前往并阅读您分享的链接。 - Unheilig
这个答案已经不是最新的了,你应该查看 https://dev59.com/Wl4d5IYBdhLWcg3wLf_P#39779643 - suleymancalik

5

泛型类型别名 - SE-0048

状态:已实现(Swift 3)

解决方案很简单:允许类型别名引入类型参数,并在其定义范围内。这使得我们可以表达像下面这样的内容:

typealias StringDictionary<T> = Dictionary<String, T>
typealias IntFunction<T> = (T) -> Int
typealias MatchingTriple<T> = (T, T, T)
alias BackwardTriple<T1, T2, T3> = (T3, T2, T1)

0

这里我提供一个关于typealias的示例,演示了如何在协议定义中使用typealias:希望这能帮助您理解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

嘿,@Narendra G,你认为这个解决方案也适用于其他数字类型吗? - Sentry.co

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接