第三周第一天
集合(set)
集合:没有重复的元素,无序存放哪里有空位就存在哪
let a = [1,2,3,1,2,5]
print(a)
这个打印出来是[1,2,3,1,2,5]
var a:Set<Int> = [1,2,3,1,2,5]
print(a)
这个打印出来是[1.2,3,5]
1.集合的遍历
var a:Set<Int> = [1,2,3,1,2,5]
for x in a{
print(x)
}
//用x替代集合中的元素
2.元素的添加
var a:Set<Int> = [1,2,3,5]
a.insert(100)
3.元素的删除
var a:Set<Int> = [1,2,3,5]
a.remove(2)//直接写删除的具体哪个元素
4.交集
var b:Set<Int>= [3,5,9,7,11]
var a:Set<Int> = [1,2,3,5]
print(a.intersect(b))//输出a和b的交集
5.并集
var b:Set<Int>= [3,5,9,7,11]
var a:Set<Int> = [1,2,3,5]
print(a.union(b))//输出a和b的并集
6.差集
var b:Set<Int>= [3,5,9,7,11]
var a:Set<Int> = [1,2,3,5]
print(a.subtract(b))//输出a和b的差集,a中有b中没有的元素
7.判断子集返回值是bool
var a:Set<Int> = [1,2,3,5]
let c:Set<Int>=[1,3]
print(c.isSubsetOf(a))
8.判断超集
var a:Set<Int> = [1,2,3,5]
let c:Set<Int>=[1,3]
print(a.isSupersetOf(c))
字典(Dictionary)
字典:存放键值对组合的容器,字典中的每个元素都是由两部分构成的,冒号前面是键冒号后面是值
var dict = ["abacus":"算盘","abnormal":"差错","hello":"你好"]
1.添加键值对
var dict = ["abacus":"算盘","abnormal":"差错","hello":"你好"]
dict["shit"]="狗屎"
print(dict)
//["hello": "你好", "abacus": "算盘", "shit": "狗屎", "abnormal": "差错"]
2.删除元素找指定键
var dict = ["abacus":"算盘","abnormal":"差错","hello":"你好"]
dict.removeValueForKey("hello")
//dict["hello"]=nil//两句话都可以
3.更改元素
var dict = ["abacus":"算盘","abnormal":"差错","hello":"你好"]
dict["hello"] = "牛屎"
print(dict)
//结果["hello": "牛屎", "abacus": "算盘", "abnormal": "差错"]
4.字典的遍历
var dict = ["abacus":"算盘","abnormal":"差错","hello":"你好"]
for value in dict.values{
print(value)
}
for key in dict.keys {
print("\(key)-->\(dict[key])")
}
for (key,value) in dict {
print("\(key)-->\(value)")
函数(Functions)
定义函数
func 函数名(参数名:参数类型)->返回类型{函数的执行体}
func persensName(persensName:String,alreadyGreeted:Bool=true)->String{
if alreadyGreeted{
//Swift中可以设定默认值
//如果调用函数时不输入参数就执行默认值
return "怎么又是你," + persensName + "!"
}
else{
return "你好" + persensName + "!"
}
//如果函数的返回类型不是void 那么函数中一定有return语句
}
//调用函数
//函数名(参数值)
//调用swift函数时,在默认情况下从第二个参数开始需要写函数名
print(persensName("王大锤", alreadyGreeted: true))
print(persensName("王尼玛", alreadyGreeted: false))
函数名(外部参数名 内部参数名:类型,外部参数名 内部参数名:类型)
如果不写外部参数名那么内部参数名也是外部参数名
Swift中函数的 参数列表可以是[可变参数列表](参数的个数可以是任意多个)
func sum(nums:Int...)->Int{
var total = 0
for num in nums {
total += num
}
return total
}
print(sum(15,25,35,77,88,99,58,60,120))
print(sum(25,33))
使用元组可以使函数返回多参数
func minMax(array: [Int]) -> (min: Int, max: Int) {
var currentMin = array[0]
var currentMax = array[0]
for value in array[1..<array.count] {
if value < currentMin {
currentMin = value
} else if value > currentMax {
currentMax = value
}
}
return (currentMin, currentMax)
}
let b = minMax([77,88,99,66,12,45,6,4,20])
print(b.max)
print(b.min)
如何让参数改变后再传出来,定义返回值是一种然后
func swap (inout x:Int,inout y:Int)->Void{
let temp = x
x = y
y = temp
}
var x=5,y=6
swap(&x, y: &y)
print("x=\(x)")
print("y=\(y)")
//inout - 输入输出参数(不仅将数据传入函数还要从函数中取出数据)