-
最喜歡Swift的類型轉(zhuǎn)換和過濾數(shù)組():
- 為什么呢?看了下面的例子你就明白了,看Swift和Objective-C的對(duì)比
-
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]];
}]
];
-
一灭必、數(shù)組
1.數(shù)組的初始化
-
Easily my favorite initializer for strings and array is count:repeatedValue:
2.進(jìn)制轉(zhuǎn)換>
-
十進(jìn)制的轉(zhuǎn)化
String(12, radix: 16) // 十進(jìn)制轉(zhuǎn)16進(jìn)制
String(12, radix: 8) // 十進(jìn)制轉(zhuǎn)8進(jìn)制
String(12, radix: 2) // 十進(jìn)制轉(zhuǎn)2進(jìn)制
String(12, radix: 4) // 十進(jìn)制轉(zhuǎn)4進(jìn)制
-
其他進(jìn)制的轉(zhuǎn)化
// 數(shù)字轉(zhuǎn)化后的字母是否需要大小寫
// str設(shè)置為“1 c”播瞳。如果你喜歡——即“1 C”掸刊。,大寫
String(28, radix: 16, uppercase: true) // 打印結(jié)果:"1C"
String(18, radix: 16, uppercase: true) // 打印結(jié)果:"12"
// 字符串轉(zhuǎn)化 (轉(zhuǎn)換回一個(gè)整數(shù)——記住,可選!)
let int = Int("1C", radix: 16) // 打印結(jié)果:28
-
3.數(shù)組和集合的轉(zhuǎn)化
let scores = [5, 3, 6, 1, 3, 5, 3, 9, 6] // 數(shù)組
let scoresSet = Set(scores) // 集合,從打印結(jié)果看出不會(huì)重復(fù),且集合是無序的
let uniqueScores = Array(scoresSet) // 從集合中創(chuàng)建一個(gè)數(shù)組
-
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
}
-
具體使用場(chǎng)景:
創(chuàng)建一個(gè)結(jié)構(gòu)體赢乓,有名字和color忧侧。它會(huì)自動(dòng)生成構(gòu)造方法
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 // 這樣會(huì)報(bào)錯(cuò)苍柏,需改為Color.Pink. hasValue
// 改為Color.Pink. hasValue == 打印出來的是3 // 從結(jié)果可以看出尼斧,也就是說默認(rèn)會(huì)從0開頭算起
枚舉:指定是String類型
enum Color: String {
case Unknown, Blue, Green, Pink, Purple, Red
}
MYColor.Pink.rawValue // 打印出來是"Pink"
-
二姜贡、數(shù)組排序
-
默認(rèn)排序:升序
-
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)")
}
數(shù)組的增加试吁、刪除和插入
-
+ 增加 數(shù)組與數(shù)組的增加
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] // 拼接一個(gè)數(shù)組等價(jià)于dogs.append(contentsOf: [beethoven])
dogs.append(Dog(breed: "xiaohua", age: 3)) // 拼接一個(gè)元素
-
- 刪除 主要講解刪除最后一個(gè)元素
- removeLast() 和popLast()兩者都是刪除最后一個(gè)元素并返回刪除的對(duì)象。唯一的區(qū)別看下圖打印可知楼咳,popLast()刪除返回的對(duì)象是可選值熄捍。如果數(shù)組中有空值(nil)的時(shí)候,使用removeLast()母怜,程序就會(huì)崩潰余耽。所以如果你的數(shù)組中有可能是空值,當(dāng)你嘗試刪除一個(gè)條目,使用popLast()苹熏,您可以安全地檢查返回值:
if let dog = dogs.popLast() { // do stuff with
dog}
碟贾。但是,removeLast()有removeFirst()對(duì)應(yīng)轨域,而popLast() 沒有
- removeLast() 和popLast()兩者都是刪除最后一個(gè)元素并返回刪除的對(duì)象。唯一的區(qū)別看下圖打印可知楼咳,popLast()刪除返回的對(duì)象是可選值熄捍。如果數(shù)組中有空值(nil)的時(shí)候,使用removeLast()母怜,程序就會(huì)崩潰余耽。所以如果你的數(shù)組中有可能是空值,當(dāng)你嘗試刪除一個(gè)條目,使用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)
-
數(shù)組的效率
- 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()體現(xiàn)無序性
- contains()包含關(guān)系
- remove()移除元素
- sorted(), map() and filter() 方法等
var set1 = Set<Int>([1, 2, 3, 4, 5]) // 5, 2, 3, 1, 4 集合的無序性和不重復(fù)性
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()干发,而數(shù)組恰恰相反朱巨,我想知道Why?
-
集合的交并補(bǔ)
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子集的任何一個(gè)元素都不包含在B集合中必峰。
?A.isStrictSubsetOf(B):返回true,A是B的子集,但A和B是不一樣的洪唐,兩者不能等價(jià)
?A.isStrictSupersetOf(B):返回true,如果A的所元素也在設(shè)置在B中,并且A元素中的個(gè)數(shù)小于B中元素的個(gè)數(shù),也就是A和B是不一樣的吼蚁,兩者不能等價(jià)
-
eg:舉個(gè)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:舉個(gè)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
-
集合的相加以及獲取集合中元素的個(gè)數(shù)
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,雖然不會(huì)重復(fù)出現(xiàn)桐罕,但是他可以統(tǒng)計(jì)到出現(xiàn)了幾次
print(countedSet.count(for: "Sulaco")) // 1