Swift入门笔记-泛型

时间:2024-07-16 13:25:39
// 创建一个泛型方法或者类型
func makeArray<Item>(repeating item: Item, numberOfTimes: Int) -> [Item] {
  var result = [Item]()
  for _ in 0..<numberOfTimes {
    result.append(item)
  }
  return result
}
var aes = makeArray(repeating: "knock", numberOfTimes:4)
print(aes)
// 可以从函数、方法、类、枚举、结构体创建泛型
enum OptionalValue<Wrapped> {
  case none
  case some(Wrapped)
}
var possibleInteger: OptionalValue<Int> = .none
possibleInteger = .some(100)
// 类型名称后紧接where来明确一系列需求
func anyCommonElements<T: Sequence, U: Sequence>(_ 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
  }
  b = anyCommonElements([1, 2, 3], [3])
  print(b)