Swift中的泛型类型 [英] Generic typealias in Swift

查看:131
本文介绍了Swift中的泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在haskell中,您可以这样做:

  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 typealias 目前无法与泛型一起使用。您最好的选择可能是将解析器函数封装在结构中。

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆