Swift中的泛型类型 [英] Generic typealias in Swift
问题描述
type Parser a = String - > [(a,String)]
我试图在Swift中做类似的事情。到目前为止,我没有运气写这些代码。
typealias解析器< A> =字符串 - > [(A,String)]
typealias解析器a =字符串 - > [(a,String)]
typealias Parser = String - > [(A,String)]
所以这在swift中根本不可能?如果是,还有另外一种方法来实现这种行为?
更新:现在似乎泛型类型别支持swift 3
https://github.com/apple/swift/blob/master/CHANGELOG.md
struct Parser< A> {
let f:String - > [(A,String)]
}
然后,您可以使用尾随闭包语法创建一个解析器,例如
let parser = Parser< Character> {string in return [head(string),tail(string)]}
In haskell you can do this:
type Parser a = String -> [(a, String)]
I tried to make something similar in Swift. So far I wrote these codes with no luck.
typealias Parser<A> = String -> [(A, String)]
typealias Parser a = String -> [(a, String)]
typealias Parser = String -> [(A, String)]
So is this simply impossible in swift? And if it is is there another ways to implement this behavior?
UPDATE: It seems generic typealiases are now supported in swift 3 https://github.com/apple/swift/blob/master/CHANGELOG.md
typealias
cannot currently be used with generics. Your best option might be to wrap the parser function inside a struct.
struct Parser<A> {
let f: String -> [(A, String)]
}
You can then use the trailing closure syntax when creating a parser, e.g.
let parser = Parser<Character> { string in return [head(string), tail(string)] }
这篇关于Swift中的泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!