Swift学习笔记之集合类型
集合分三种,Array,Set,Dictionary。
- Array 像JS的Array ,可以放key.
- Dictionary 对应Java的Map
数组操作
创建空的数组
var ints = [Int]();
print(ints.count);
添加数据
var ints = [Int]();
ints.append(3);
ints += [3];
print(ints);
置空
var ints = [Int]();
ints.append(3);
ints = []; //置空
print(ints);
初始化数组
var ints = Array(repeating: 2, count: 4);//重复2,重复4遍
print(ints);
数组合并
var ints = Array(repeating: 2, count: 4);//重复2,重复4遍
var otherInts = Array(repeating: 3, count: 3);
var together = ints + otherInts;
print(together);
插入某个位置
var ints = Array(repeating: 2, count: 4);
ints.insert(12, at: 1);
print(ints);
移除最后一个元素
var ints = [2,3,4,5];
ints.removeLast();
print(ints);
循环获取数组
var ints = [2,3,4,5];
for myInt in ints{
print(myInt);
}
循环获取数组值包含index
var names = ["Tomas","HaliPoTe"]
for(index,name) in names.enumerated(){
print("index:\(index) name:\(name)");
}
设置数组的值
var ints = [2,3,4,5];
ints[0] = 10086; //设置0位的值
ints[1...2] = [1007,1008,300]; //设置1到2的值,同时把300插入到后面
print(ints);
集合
NOTE
Swift’s Set type is bridged to Foundation’s NSSet class.
For more information about using Set with Foundation and Cocoa, see Using Swift with Cocoa and Objective-C (Swift 3).
基本数据类型例如Int 这些,已经实现了hashable ,如果是自己的类型必须要自己实现hashable ,和Java重写hashvalue方法感觉差不错
操作
//创建一个空的集合
var emptySet = Set<String>();
//创建并同时初始化集合
var myfavorice: Set<String> = ["苹果","荔枝","西瓜"];
//添加元素
myfavorice.insert("李子");
//置空
myfavorice = [];
//根据类型自动匹配创建
var sex:Set = ["男","女"];
//remove
myfavorice.remove("苹果");
//迭代
for name in myfavorice{
print(name);
}
//集合操作
var classA:Set<String> = ["哆啦A梦","静香","小夫"];
var classB:Set<String> = ["哆啦A梦","大熊","小夫"];
//交集
print("交集:\(classA.intersection(classB))");
//对称差
print("对称差:\(classB.symmetricDifference(classA))");
//并集
print("并集:\(classA.union(classB))");
//差集
print("差集:\(classA.subtracting(classB))");
//相等
print(classB == classA);
let houseAnimals: Set = ["🐶", "🐱"]
let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱","鸡"]
let cityAnimals: Set = ["够"]
//是不是farm 的子集
print(houseAnimals.isSubset(of: farmAnimals));
//farm的超集是不是house
print(farmAnimals.isSuperset(of: houseAnimals));
//是否没有任何的交集
print(farmAnimals.isDisjoint(with: cityAnimals));