【Swift 60秒】10 - Sets

本文介绍了Swift中的Set数据结构,它是一个不保证顺序且不允许重复元素的集合。Set的创建、无序性以及不允许重复的特性通过实例进行了展示。例如,尝试向Set中添加重复元素时,多余的项会被忽略。了解这些基础知识对于Swift编程至关重要。
摘要由CSDN通过智能技术生成

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 搜索即可~


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

豪冷啊

你的鼓励是对我的认可!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值