复习总结 7.25
0. let/var 常量/变量
1. 数组
let定义的数组,内容不可变
let arr: Array<Int> = Array<Int>() //完整版
let arr = Array<Int>()
let arr = [Int]()
let arr = [1, 2, 3]
//根据位置进行操作,元素按顺序排列
arr[1]
2. 字典
let dict: Dictionary<String, Int> = Dictionary<String, Int>()
let dict = Dictionary<String, Int>()
let dict = [String:Int]()
let dict = ["key1":1, "key2":2]
//根据Key(键)操作,元素没有顺序
dict["key2"]
3. 循环
范围
for i in 0...9 {
}
for i in 0..<10 {
}
let arr = [1, 2, 3]
for i in arr {
}
let dict = ["key1":1, "key2":2]
for pair in dict {
print(pair.0, pair.1)
}
for (key, value) in dict {
print(key, value)
}
var i = 10
while i < 10 {
i += 1 //修改循环变量,使得循环能够终止
}
i = 10
repeat {
i += 1
} while i < 10
4. 条件判断
var i = 10
var j = 20
if i < j {
}
else if i < 10{
}
else {
}
运算符号 >, <, ==, !=, >=, <=
&&(与), ||(或), !(非)
var a = false
var b = false
a && b: 只有当a和b都为真,表达式为真
a || b: 只有当a和b都为假,表达式为假
!a: 真变假,假变真, 取反值
var i = 20
var j = 30
(i > 20) && (i < 10): 假
(i > 10) && (i < 20): 假
(i > 10) && (i < 30): 真
(i > 30) || (i < 30): 真
var b = false
!b
5. switch
var i = 1
switch i {
case 0..<10:
print("xxx")
fallthrough
case 1:
print("yyy")
default:
print("zzz")
}
6. enum 枚举类型
enum Weekday {
case Monday
case Thuesday
}
var w: Weekday = Weekday.Monday
w = .Thuesday
7. Optional
var i: Int? //必须使用!手动拆包
i = 123
var j = i! + 123
var k: Int! //自动拆包
k = 34
var m = k + 34
8. struct
struct Student {
var name: String
var age: Int
}
//值类型
var st01 = Student(name: "Lisi", age: 23)
var st02 = st01 //复制,变成两个
st01.name = "Zhangsan"
9. class
class Rectangle {
var width: Double! //存储属性
var height: Double! {
willSet {
print("\(newValue) : \(height)")
}
didSet {
print("\(height)")
}
}
var area: Double {
get {
return width * height
}
set {
}
}
}
类自动生成的构造函数,没有参数
封装、继承、多态
class Animal {
func eat() {}
}
//单继承
class Dog: Animal {
func newFunc() {}
override func eat() {}
}
class Cat: Animal {
override func eat() {}
}
var ani: Animal
ani = Animal()
ani.eat()
ani = Dog()
ani.eat()
ani = Cat()
ani.eat()
10. protocol 协议
约定一个类型必须要具备某种功能
约束
可以有方法、计算属性
不能有存储属性、不能实现方法
protocol BiteProtocol {
var a: Int { get set }
var b: Int { get }
func bite()
}
class Tiger : BiteProtocol {}
var bp: BiteProtocol = Tiger()
11. extension 扩展
1. 将类拆分成多个部分
2. 给已有类型增加新功能
12. 运算符重载
func +(lhs: Tiger, rhs: Tiger) -> Tiger {
return ....
}
13. 闭包
封装一段可执行代码
匿名函数
let c1 = {
(a: Int) -> String in
return "\(a)"
}
//闭包需要在调用的时候才会执行
c1(23)
let c2: (Int) -> String = {
"\($0)"
}
c2(34)
func createClosure() -> (Int) -> String {
return { "\($0)" }
}
let c3 = createClosure()
c3(56)
createClosure()(56)
let v = {
(a: Int) -> String in
return "\(a)"
}(45)
14. lazy
第一次使用时才加载
15. 泛型(Generics)
16. 元组
let a = (1, 3)
a.0
let b = (first: 23, second: 45)
b.first
17. Any/AnyObject 任意类型/
根据后面调用的值,自动转换类型
18. inout
19. defer 延时执行
后加入的先执行
20. final
父类加入final,表示不能在子类中被重写(覆盖)
21. public/internal/private
22. @autoclosure
自动封包 --- 自动将表达式封装成闭包
网友评论