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])
  • 相关阅读:
    POJ 2976 Dropping tests
    【学习笔记-中国剩余定理】POJ1006 Biorhythms
    2017.10.6北京清北综合强化班DAY6
    P1607 [USACO09FEB]庙会班车Fair Shuttle
    2017.10.5北京清北综合强化班DAY5
    洛谷 P1379 八数码难题
    A. 拼音魔法
    A
    K
    A
  • 原文地址:https://www.cnblogs.com/atong/p/3767522.html
Copyright © 2011-2022 走看看