美文网首页Swift学习笔记swift基础
swift基础—泛型(Generics)

swift基础—泛型(Generics)

作者: 莽原奔马668 | 来源:发表于2017-04-12 16:55 被阅读68次

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

func repeatItem(repeating item: Item, numberOfTimes: Int) -> [Item] {

  var result = [Item]()

  for _ in 0..< numberOfTimes {

    result.append(item)

  }

  return result

}

repeatItem(repeating: "knock", numberOfTimes:4)

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

// 重新实现 Swift 标准库中的可选类型

enum OptionalValue {

  case None

  case Some(Wrapped)

}

var possibleInteger: OptionalValue = .None

possibleInteger = .Some(100)

在类型名后面使用“where”来指定对类型的需求,比如,限定类型实现某一个协议,限定两个类型是相同的,或者限定某个类必须有一个特定的父类。

func anyCommonElements(_ lhs: T, _ rhs: U) -> Bool

  where T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element {

    for lhsItem in lhs {

      for rhsItem in rhs {

        if lhsItem == rhsItem {

          return true

        }

      }

    }

  return false

}

anyCommonElements([1, 2, 3], [3])

"<T:Equatable>"和"<T>... where T: Equatable>"是等价的。

相关文章

网友评论

    本文标题:swift基础—泛型(Generics)

    本文链接:https://www.haomeiwen.com/subject/hnymattx.html