2025年3月30日 星期日 甲辰(龙)年 月廿九 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Swift

Swift泛型示例

时间:05-17来源:作者:点击数:93

在尖括号里写一个名字来创建一个泛型函数或者类型。 

  • func repeat<ItemType>(item: ItemType, times: Int) -> ItemType[] {
  • var result = ItemType[]()
  • for i in 0..times {
  • result += item
  • }
  • return result
  • }
  • repeat("knock", 4)

你也可以创建泛型类、枚举和结构体。 

  • // Reimplement the Swift standard library's optional type
  • enum OptionalValue<T> {
  • case None
  • case Some(T)
  • }
  • var possibleInteger: OptionalValue<Int> = .None
  • possibleInteger = .Some(100)

在类型名后面使用where来指定一个需求列表——例如,要限定实现一个协议的类型,需要限定两个类型要相同,或者限定一个类必须有一个特定的父类。 

  • func anyCommonElements <T, U where T: Sequence, U: Sequence, T.GeneratorType.Element: Equatable, T.GeneratorType.Element == U.GeneratorType.Element> (lhs: T, rhs: U) -> Bool {
  • for lhsItem in lhs {
  • for rhsItem in rhs {
  • if lhsItem == rhsItem {
  • return true
  • }
  • }
  • }
  • return false
  • }
  • anyCommonElements([1, 2, 3], [3])

练习:修改anyCommonElements函数来创建一个函数,返回一个数组,内容是两个序列的共有元素。

简单起见,你可以忽略where,只在冒号后面写接口或者类名。<T: Equatable>和<T where T: Equatable>是等价的。

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门