Swift基础之集合

import UIKit

/// Set:一组无序的,不重复的元素。 和Dictionary一样,Set通过哈希表实现,并拥有类似的性能和要求,每个元素必须满足Hashable
///Set遵守 ExpressibleByArrayLiteral协议,所以可以用数组字面量的方式初始化一个集合
let naturals = [1, 2, 3, 2]
print(naturals)

///Mark: 集合代数
var set1: Set = [1, 2, 4, 6, 8]
let set2: Set = [1, 3, 5, 7, 9]

//交集
let intersection = set1.intersection(set2)
print(intersection)

//补集
let subtracting = set1.subtracting(set2)
print(subtracting)

//并集
set1.formUnion(set2)
print(set1)

///OptionSet
struct shippingOptions: OptionSet {
  let rawValue: Int
  static let nextDay = shippingOptions(rawValue: 1 << 0)
  static let secondDay = shippingOptions(rawValue: 1 << 1)
  static let priority = shippingOptions(rawValue: 1 << 2)
  static let standard = shippingOptions(rawValue: 1 << 3)
  static let express: shippingOptions = [.nextDay, .standard]
  static let all: shippingOptions = [.express, .priority, .standard]
}

let a = shippingOptions(rawValue: 10)
print([a, .nextDay])

//TODO: SetAlgebra, OptionSet

/// Mark:索引集合: IndexSet
///IndexSet 比 Set<Int>更高效,因为内部使用了一组范围列表进行实现
///例如: 1000个用户,用Set<Int>表示为1000个不同的元素,而IndexSet会存储连续的范围,也就是说在取0 - 500行的情况下,IndexSet只存储 首位和末位两个整数(0,500)
var indices = IndexSet()
indices.insert(integersIn: 1..<5)
indices.insert(integersIn: 11..<15)
print(indices.rangeView)
let evenIndices = indices.filter { _ in return true }
print(evenIndices)

// Mark: 去重  闭包中使用集合
extension Sequence where Element: Hashable {
  func unique() -> [Element] {
    var seen: Set<Element> = []
    return filter({ element -> Bool in
      if seen.contains(element) {
        return false
      } else {
        seen.insert(element)
        return true
      }
    })
  }
}

let uniqueue = [1, 2, 3, 4, 5, 6 ,3, 4, 5].unique()
print(uniqueue)



©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容