zoukankan      html  css  js  c++  java
  • Swift 泛型(generics)

    Swift 使用<>来声明泛型函数或泛型类型:

    1 func repeat<ItemType>(item: ItemType, times: Int) -> ItemType[] {
    2     var result = ItemType[]()
    3     for i in 0..times {
    4         result += item
    5     }
    6     return result
    7 }
    8 repeat ("knock", 4)

    Swift 也支持在类、枚举和结构中使用泛型:

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

    有时需要对泛型做一些需求(requirements),比如需求某个泛型类型实现某个接口或继承自某个特定类型、两个泛型类型属于同一个类型等等,Swift 通过where描述这些需求:

     1 func anyCommonElements <T, U where T: Sequence, U: Sequence, T.GeneratorType.Element: Equatable, T.GeneratorType.Element == U.GeneratorType.Element> (lhs: T, rhs: U) -> Bool {
     2     for lhsItem in lhs {
     3         for rhsItem in rhs {
     4             if lhsItem == rhsItem {
     5                 return true
     6             }
     7         }
     8     }
     9     return false
    10 }
    11 anyCommonElements ([1, 2, 3], [3])
  • 相关阅读:
    欧拉图
    hdu2544 迪杰斯特拉题目优化
    迪杰斯特拉--数组模拟邻接表优化
    快速幂
    四叉树 bnuoj
    逆康拓展开展开
    全排列 STL
    魔板拼图
    「luogu4366」最短路
    「国家集训队」稳定婚姻
  • 原文地址:https://www.cnblogs.com/atong/p/3767522.html
Copyright © 2011-2022 走看看