美文网首页
Swift 集合类型之集合

Swift 集合类型之集合

作者: 点滴86 | 来源:发表于2016-08-03 19:43 被阅读8次

创建空集合

import UIKit

// 创建空集合
var letters = Set<Character>()
print("letters is of type Set<Character> with \(letters.count) items")

letters.insert("a")

letters = []

创建有元素的集合

// 创建有元素的集合
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]

print("I have \(favoriteGenres.count) favorite music genres")

// 集合空的判断
if favoriteGenres.isEmpty {
    print("As far as music goes, I'm not picky.")
} else {
    print("I have particular music preferences.")
}

单个集合的基本操作

// 集合插入元素
favoriteGenres.insert("Jazz")

// 集合移除元素
if let removeGenre = favoriteGenres.remove("Rock") {
    print("\(removeGenre)? I'm over it.")
} else {
    print("I never much cared for that.")
}

// 集合包含元素
if favoriteGenres.contains("Funk") {
    print("I get up on the good foot.")
} else {
    print("It's too funky in here.")
}

遍历集合

// 遍历集合
for genre in favoriteGenres {
    print("\(genre)")
}

print("排序之后输出")
for genre in favoriteGenres.sort() {
    print("\(genre)")
}

console log 如下:


屏幕快照 2016-08-03 下午7.39.32.png

多个集合的操作

// 集合的操作
let oddDigits: Set = [1, 3, 5, 7, 9]
let evenDigits: Set = [0, 2, 4, 6, 8]
let singleDigitPrimeNumbers: Set = [2, 3, 5, 7]

// 两个集合的并集
let unionSet = oddDigits.union(evenDigits).sort()
print(unionSet)

// 两个集合的交集
let interSectSet = oddDigits.intersect(evenDigits).sort()
print(interSectSet)

// 在A集合里面但是不在B集合里面
let subtractingSet = oddDigits.subtract(singleDigitPrimeNumbers).sort()
print(subtractingSet)

console log 如下:


屏幕快照 2016-08-03 下午7.40.29.png

集合关系的操作

let houseAnimals: Set = ["🐶", "🐱"]
let farmAnimals: Set = ["🐮", "🐔", "🐏", "🐶", "🐱"]
let cityAnimals: Set = ["🐦", "🐭"]

// houseAnimals 是 farmAnimals 的子集
houseAnimals.isSubsetOf(farmAnimals)

// farmAnimals 是 houseAnimals 的父集
farmAnimals.isSupersetOf(houseAnimals)

// farmAnimals 和 cityAnimals 没有交集
farmAnimals.isDisjointWith(cityAnimals)

相关文章

  • Swift 集合类型之集合

    创建空集合 创建有元素的集合 单个集合的基本操作 遍历集合 console log 如下: 多个集合的操作 con...

  • iOS开发 - 「Swift 学习」Dictionary集合类型

    Swift语言Dictionary集合类型的创建、遍历 Swift 的字典类型是无序集合类型 Dictionary...

  • Swift语法--集合类型

    集合类型 提供三种集合,数组、合集、字典。Swift中的集合总是明确能储存的值的类型。 Swift中的集合是采用泛...

  • Swift -- 集合类型

    Swift 集合类型 Swift 语言提供Arrays、Sets和Dictionaries三种基本的集合类型用来存...

  • Swift3.x - 集合类型

    集合类型的介绍Swift中提供三种集合类型:数组(Arrays)、集合(Sets)和字典(Dictionaries...

  • Swift5.1集合类型

    4.集合类型 集合类型:Swift 语⾔提供数组(Array)、集合(Set)和字典(Dictionary)三种基...

  • 4、Swift集合类型

    集合类型 Swift 语言提供数组(Array)、集合(Set)和字典(Dictionary)三种基本的集合类型用...

  • Swift - 集合类型

    集合类型 Swift 语言提供数组(Array)、集合(Set)和字典(Dictionary)三种基本的集合类型用...

  • 集合类型

    集合类型 Swift提供了三种主要的集合类型,称为数组,集合和字典,用于存储值的集合。数组是有序的值集合。集合是唯...

  • Swift编程五(集合类型)

    案例代码下载 集合类型 Swift提供三种主要的集合类型,为数组,集合和字典,用于存储集合值。数组是有序的值集合。...

网友评论

      本文标题:Swift 集合类型之集合

      本文链接:https://www.haomeiwen.com/subject/ojtcsttx.html