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])
  • 相关阅读:
    前端 ---- ajax(2)
    前端 ---- ajax(1)
    前端 ---- 博客项目
    Vue 重复进入相同路由消除警报
    axios和message注册全局变量不一样
    element-ui 的input组件 @keyup.enter事件的添加办法
    前端 ----Express
    MyBatis学习一
    SpringMVC学习一
    JVM学习一
  • 原文地址:https://www.cnblogs.com/atong/p/3767522.html
Copyright © 2011-2022 走看看