swift3.0之集合Set

本文深入探讨Swift中的集合(Set),包括创建、访问、修改集合的方法,集合的遍历方式,集合操作如交集、并集、差集等,以及如何判断集合成员关系和相等。通过实例演示了集合的基本用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

集合(Sets):用来存储相同类型并且没有确定顺序的值。当集合元素顺序不重要时或者希望确保每个元素只出现一次时可以使用集合而不是数组。

 

创建和构造一个空的集合

var letters = Set<Character>()
print("letters is of type Set<Character> with \(letters.count) items.")
// 打印 "letters is of type Set<Character> with 0 items."

用数组字面量创建集合

var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
// favoriteGenres 被构造成含有三个初始值的集合

访问和修改一个集合

///获取Set中元素的数量
print("I have \(favoriteGenres.count) favorite music genres.")

///使用布尔属性isEmpty作为一个缩写形式去检查count属性是否为0
if favoriteGenres.isEmpty {
    print("As far as music goes, I'm not picky.")
}

///添加一个新元素
favoriteGenres.insert("Jazz")

///删除一个元素
if let removedGenre = favoriteGenres.remove("Rock") {
    print("\(removedGenre)? I'm over it.")
} else {
    print("I never much cared for that.")
}
// 打印 "Rock? I'm over it."

///检查Set中是否包含一个特定的值
if favoriteGenres.contains("Funk") {
    print("I get up on the good foot.")
} else {
    print("It's too funky in here.")
}
// 打印 "It's too funky in here."

遍历集合

///method1
for genre in favoriteGenres {
    print("\(genre)")
}

///method2
//Swift 的Set类型没有确定的顺序,为了按照特定顺序来遍历一个Set中的值可以使用sorted()方法,它将返回一个有序数组,这个数组的元素排列顺序由操作符'<'对元素进行比较的结果来确定.
for genre in favoriteGenres.sorted() {
    print("\(genre)")
}
// prints "Classical"
// prints "Hip hop"
// prints "Jazz

集合操作

  • 使用intersection(_:)方法根据两个集合中都包含的值创建的一个新的集合。
  • 使用symmetricDifference(_:)方法根据在一个集合中但不在两个集合中的值创建一个新的集合。
  • 使用union(_:)方法根据两个集合的值创建一个新的集合。
  • 使用subtracting(_:)方法根据不在该集合中的值创建一个新的集合。
let oddDigits: Set = [1, 3, 5, 7, 9]
let evenDigits: Set = [0, 2, 4, 6, 8]
let singleDigitPrimeNumbers: Set = [2, 3, 5, 7]

oddDigits.union(evenDigits).sorted()
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
oddDigits.intersection(evenDigits).sorted()
// []
oddDigits.subtracting(singleDigitPrimeNumbers).sorted()
// [1, 9]
oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted()
// [1, 2, 9]

集合成员关系和相等

  • 使用“是否相等”运算符(==)来判断两个集合是否包含全部相同的值。
  • 使用isSubset(of:)方法来判断一个集合中的值是否也被包含在另外一个集合中。
  • 使用isSuperset(of:)方法来判断一个集合中包含另一个集合中所有的值。
  • 使用isStrictSubset(of:)或者isStrictSuperset(of:)方法来判断一个集合是否是另外一个集合的子集合或者父集合并且两个集合并不相等。
  • 使用isDisjoint(with:)方法来判断两个集合是否不含有相同的值(是否没有交集)。
  • let houseAnimals: Set = ["?", "?"]
    let farmAnimals: Set = ["?", "?", "?", "?", "?"]
    let cityAnimals: Set = ["?", "?"]
    
    houseAnimals.isSubset(of: farmAnimals)
    // true
    farmAnimals.isSuperset(of: houseAnimals)
    // true
    farmAnimals.isDisjoint(with: cityAnimals)
    // true

     

转自:http://www.swift51.com/swift3.0.html

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值