-
最喜欢Swift的类型转换和过滤数组():
- 为什么呢?看了下面的例子你就明白了,看Swift和Objective-C的对比
-
Swift
let myCustomViews = self.subViews.flatMap {
$0 as MyCustomView
}
-
OC
NSArray<MyCustomView *> *myCustomViews = (NSArray<MyCustomView *> *) [self.subViews filteredArrayUsingPredicate: [NSPredicate predicateWithBlock:^BOOL(id _Nonnull evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
return [evaluatedObject isKindOfClass:[MyCustomView class]];
}]
];
-
一、数组
1.数组的初始化
-
Easily my favorite initializer for strings and array is count:repeatedValue:
2.进制转换>
-
十进制的转化
String(12, radix: 16) // 十进制转16进制
String(12, radix: 8) // 十进制转8进制
String(12, radix: 2) // 十进制转2进制
String(12, radix: 4) // 十进制转4进制
-
其他进制的转化
// 数字转化后的字母是否需要大小写
// str设置为“1 c”。如果你喜欢——即“1 C”。,大写
String(28, radix: 16, uppercase: true) // 打印结果:"1C"
String(18, radix: 16, uppercase: true) // 打印结果:"12"
// 字符串转化 (转换回一个整数——记住,可选!)
let int = Int("1C", radix: 16) // 打印结果:28
-
3.数组和集合的转化
let scores = [5, 3, 6, 1, 3, 5, 3, 9, 6] // 数组
let scoresSet = Set(scores) // 集合,从打印结果看出不会重复,且集合是无序的
let uniqueScores = Array(scoresSet) // 从集合中创建一个数组
-
4.枚举
-
写法1:
-
enum Color {
case Unknown
case Blue
case Green
case Pink
case Purple
case Red
}
-
写法2:更偏向于第2种写法
enum Color {
case Unknown, Blue, Green, Pink, Purple, Red
}
-
具体使用场景:
创建一个结构体,有名字和color。它会自动生成构造方法
struct Boy {
let name: String
let color: Color
}
- 如何使用:我们不需要使用UIColor. Pink,可以直接.Pink
let 明哥 = Boy(name: "明哥", color: . Green)
let 路西 = Boy(name: "My Girl Friend", color: . Purple)
Raw values
enum Planet: Int { // 枚举
case Mercury = 1 ,Venus ,Earth ,Mars ,Unknown
}
let ttt = Planet.Earth.rawValue // 是可选值,不一定有
let mars = Planet(rawValue: 4) ?? Planet.Unknown // 打印Mars
let mars1 = Planet(rawValue: 7) ?? Planet.Unknown // 打印Unknown
值得注意的是:枚举:如果枚举没有指定类型
enum Color {
case Unknown, Blue, Green, Pink, Purple, Red
}
let pink = Color.Pink. rawValue // 这样会报错,需改为Color.Pink. hasValue
// 改为Color.Pink. hasValue == 打印出来的是3 // 从结果可以看出,也就是说默认会从0开头算起
枚举:指定是String类型
enum Color: String {
case Unknown, Blue, Green, Pink, Purple, Red
}
MYColor.Pink.rawValue // 打印出来是"Pink"
-
二、数组排序
-
默认排序:升序
-
let names = ["Dabitha", "Taylor", "Ahomas", "Ximothy", "Hobias", "Tyler"] names.sorted()
let numbers = [5, 3, 1, 9, 5, 2, 7, 8]
let lowest = numbers.min() // 找出最小值1
let highest = numbers.max() // 找出最大值9
numbers.sorted() //排序
-
升序和降序的可掌控
let names = ["Dabitha", "Taylor", "Ahomas", "Ximothy", "Hobias", "Tyler"]
let sortNames = names.sorted {
print("Comparing \($0) and \($1)")
if ($0 == "Ximothy") {
return true
} else {
return $0 < $1
}
}
print(sortNames)
操作符重载
-
控制器外边方法
struct Dog: Comparable {
var breed: String
var age: Int
}
func <(lhs: Dog, rhs: Dog) -> Bool {
return lhs.age < rhs.age
}
func ==(lhs: Dog, rhs: Dog) -> Bool {
return lhs.age == rhs.age
}
- ####控制器viewDidLoad()方法中
override func viewDidLoad() {
super.viewDidLoad()
let poppy = Dog(breed: "Poodle", age: 5)
let rusty = Dog(breed: "Labrador", age: 2)
let rover = Dog(breed: "Corgi", age: 11)
let dogs = [poppy, rusty, rover]
let newDogs = dogs.sorted()
print("排序前:\(dogs)")
print("=============")
print("排序后:\(newDogs)")
}
数组的增加、删除和插入
-
+ 增加 数组与数组的增加
let poppy = Dog(breed: "Poodle", age: 5)
let rusty = Dog(breed: "Labrador", age: 2)
let rover = Dog(breed: "Corgi", age: 11)
var dogs = [poppy, rusty, rover]
let beethoven = Dog(breed: "St Bernard", age: 8)dogs += [beethoven] // 拼接一个数组等价于dogs.append(contentsOf: [beethoven])
dogs.append(Dog(breed: "xiaohua", age: 3)) // 拼接一个元素
-
- 删除 主要讲解删除最后一个元素
- removeLast() 和popLast()两者都是删除最后一个元素并返回删除的对象。唯一的区别看下图打印可知,popLast()删除返回的对象是可选值。如果数组中有空值(nil)的时候,使用removeLast(),程序就会崩溃。所以如果你的数组中有可能是空值,当你尝试删除一个条目,使用popLast(),您可以安全地检查返回值:
if let dog = dogs.popLast() { // do stuff with
dog}
。但是,removeLast()有removeFirst()对应,而popLast() 没有
- removeLast() 和popLast()两者都是删除最后一个元素并返回删除的对象。唯一的区别看下图打印可知,popLast()删除返回的对象是可选值。如果数组中有空值(nil)的时候,使用removeLast(),程序就会崩溃。所以如果你的数组中有可能是空值,当你尝试删除一个条目,使用popLast(),您可以安全地检查返回值:
let popDog = dogs.popLast()
print("打印popDog = \(popDog)")
let removeDog = dogs.removeLast()
print("打印removeDog = \(removeDog)")
-
插入
// newElement: 要插入的元素 at: 要插入的位置
// dogs.insert(<#T##newElement: Element##Element#>, at: <#T##Int#>)
dogs.insert(Dog(breed: "huazai", age: 4), at: 0)
-
数组的效率
- Array和ContiguousArray的比较
let array2 = Array<Int>(1...1000000)
let array3 = ContiguousArray<Int>(1...1000000)
var start = CFAbsoluteTimeGetCurrent()
array2.reduce(0, +) // 50500000
var end = CFAbsoluteTimeGetCurrent() - start
print("array Took \(end) seconds")
start = CFAbsoluteTimeGetCurrent()
array3.reduce(0, +) // 50500000
end = CFAbsoluteTimeGetCurrent() - start
print("ContiguousArray Took \(end) seconds")
-
三、Set集合
- 集合的方法
- insert()体现无序性
- contains()包含关系
- remove()移除元素
- sorted(), map() and filter() 方法等
var set1 = Set<Int>([1, 2, 3, 4, 5]) // 5, 2, 3, 1, 4 集合的无序性和不重复性
var array1 = Array(set1) // 5, 2, 3, 1, 4
var set2 = Set(array1) // 5, 2, 3, 1, 4
for number in set1 {
print(number) // 5, 2, 3, 1, 4
}
for number in set1.sorted() {
print(number) // 1, 2, 3, 4, 5
}
奇怪的是Set有popFirst(),没有popLast(),而数组恰恰相反,我想知道Why?
-
集合的交并补
let spaceships1 = Set(["Serenity", "Nostromo", "Enterprise"])
let spaceships2 = Set(["Voyager", "Serenity", "Executor"])
let union = spaceships1.union(spaceships2) // 并集
let intersection = spaceships1.intersection(spaceships2) // 交集
let difference = spaceships1.symmetricDifference(spaceships2) // 除交集以外的集合
-
集合的其他方法
• A.isSubsetOf(B): returns true if all of set A's items are also in set B.
• A.isSupersetOf(B): returns true if all of set B's items are also in set A.
• A.isDisjointWith(B): returns true if none of set B's items are also in set A.
• A.isStrictSubsetOf(B): returns true if all of set A's items are also in set B, but A and B are not equal
• A.isStrictSupersetOf(B): returns true if all of set B's items are also in set A, but A and Bare not equal
#### 翻译:####
•A.isSubset(of: B):返回true,A是B的子集,A和B是可以是一样的。
•A.isSuperset(of: B):返回true,A是B的父集, A和B是可以是一样的。
•A.isDisjoint(with:B):返回true,A子集的任何一个元素都不包含在B集合中。
•A.isStrictSubsetOf(B):返回true,A是B的子集,但A和B是不一样的,两者不能等价
•A.isStrictSupersetOf(B):返回true,如果A的所元素也在设置在B中,并且A元素中的个数小于B中元素的个数,也就是A和B是不一样的,两者不能等价
-
eg:举个1
var spaceships1 = Set(["Serensdaity", "Nostromo", "Enterprise"])
let spaceships2 = Set(["Voyager", "Serenity", "Executor"])
let spaceships = Set(["Voyager", "Serenity"])
spaceships.isSubset(of: spaceships2) // true
spaceships.isSuperset(of: spaceships2) // false
spaceships1.isDisjoint(with: spaceships2) // trues
paceships.isStrictSubset(of: spaceships2) // true
spaceships.isSuperset(of: spaceships2) // false
-
eg:举个2
let spaceships1 = Set(["Serenity", "Nostromo", "Enterprise"])
let spaceships2 = Set(["Voyager", "Serenity", "Star Destroyer"])
let spaceships3 = Set(["Galactica", "Sulaco", "Minbari"])
let spaceships1and2 = spaceships1.union(spaceships2)
spaceships1.isSubsetOf(spaceships1and2) // true
spaceships1.isSubsetOf(spaceships1) // true
spaceships1.isSubsetOf(spaceships2) // false
spaceships1.isStrictSubsetOf(spaceships1and2) // true
spaceships1.isStrictSubsetOf(spaceships1) // false
spaceships1and2.isSupersetOf(spaceships2) // true
spaceships1and2.isSupersetOf(spaceships3) // false
spaceships1and2.isStrictSupersetOf(spaceships1) // true
spaceships1.isDisjointWith(spaceships2) // false
-
集合的相加以及获取集合中元素的个数
var spaceships = ["Serenity", "Nostromo", "Enterprise"]
spaceships += ["Voyager", "Serenity", "Star Destroyer"]
spaceships += ["Galactica", "Sulaco", "Minbari"]
let countedSet = NSCountedSet(array: spaceships)
print(countedSet.count(for: "Serenity")) // 2,虽然不会重复出现,但是他可以统计到出现了几次
print(countedSet.count(for: "Sulaco")) // 1