【Swift 60秒】10 - Sets

0x00 Lesson

Sets are collections of values just like arrays, except they have two differences:

  1. Items aren’t stored in any order; they are stored in what is effectively a random order.
  2. No item can appear twice in a set; all items must be unique.

You can create sets directly from arrays, like this:

let colors = Set (["red", "green", "blue"])

When you look at the value of colors inside the playground output you’ll see it doesn’t match the order we used to create it. It’s not really a random order, it’s just unordered - Swift makes no guarantees about its order. Because they are unordered, you can’t read values from a set using numerical positions like you can with arrays.

If you try to insert a duplicate item into a set, the duplicates get ignored.
For example:

let colors2 = Set ("red", "green", "blue", "red", "blue"])

The final colors2 set will still only include red, green, and blue once.


0x01 Test

01 - This will create a set with two items - true or false?

var names = Set(["sean", "Paul"])

02

var colors = Set(["Red", "Green", "Red"])

03

var attendees = Set([100, 100, 101, 100])

04

var scores = Set([9, 10])

05

var readings = Set([true, false, true, true])

06

let staffReviews = Set([1, 2, 1, 2, 3])

07

let earthquakeStrengths = Set(1,1, 2, 2)

08

let averageHeights = Set([1.71, 1.72, 1.73])

Answer:
01 - true
02 - true
03 - true
04 - true
05 - true
06 - false
07 - false. Set([1, 1, 2, 2])
08 - false


0x02 我的小作品

欢迎体验我的作品之一:小五笔
五笔学习好帮手
App Store 搜索即可~


猜你喜欢

转载自blog.csdn.net/xjh093/article/details/126827484