swift语法
类型(swift一切皆为Object的子类,即便是int类型,默认值null)
一类
- Int
- UInt(无符号Int)
- Float(32位)
- Double(64位)
- String
- Bool
- Character
- typealias(别名)
- Optional(可选类型:有值或nil)
二类
class(类)
1 可以extends
2 引用传递
1
2
3
4
5
6
7class Test{
var a:Int = 1
let b:Int = 2
func testFun(arg1:Int)->Bool{
return true;
}
}struct(结构体)
1 不能继承
2 值传递
1
2
3
4
5
6
7struct Test{
var a:Int = 1
let b:Int = 2
func testFun(arg1:Int)->Bool{
return true;
}
}协议(protocol,即为java中的接口)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28protocol TestP{
var marks: Int { get set }// 声明后加上{ set get }来表示属性是可读可写的
var result: Bool { get }
func attendance() -> String // 不能有方法体
init(arg:String) // 能定义构造方法
}
//
class TestC:TestP{
var marks = 1
var result = false
func attendance()->String(){
//
}
required init(argument:String){ // 使用required修饰符可以保证所有的遵循该协议的子类也必须实现此构造方法
print(argument)
}
}
//
struct TestS:TestP{
var marks = 1
var result = false
func attendance()->String(){
//
}
init(argument:String){ // 结构体不需要required关键字
print(argument)
}
}
非空安全
定义
1 | var test? = null // 不需要显示定义 |
非空判断
- 安全调用运算符(?.)
- 强制解包(!.)
- Elvis运算符(??)
- if let test = arg {// 非空条件下的业务逻辑}
- guard let test = arg {// 为空条件下的业务逻辑}
操作符
==
1 | 内容相等为treu(不管内存地址) |
===
1 | 内存地址相等为true |
构造方法
- 非Optional属性都需要在有初始值,如果定义时没有赋值,需要构造函数里赋值。
- 子类属性赋值之后构造函数需要调用父类构造函数。
- 构造函数可以重载。
1
2
3
4
5
6
7
8
9
10
11
12
13
14class Test : TestFather{
var v : String
// 构造函数
init(){
v = "hello"
super.init()
}
// 构造函数重载
init(arg : String){
v = arg
super.init()
}
}
析构函数(OC采用ARC引用计数实现垃圾回收)
1 | class Test : TestFather{ |
常量
- let 定义常量
- static let 定义静态常量
1
2
3
4class Test : TestFather{
let v1:String = "h"
static let v2:String = "h"
}
类定义
1 | class Test{ |
定义枚举
1 | enum Test{ |
变量定义
1 | class Test{ |
方法定义
1 | class Test{ |
单例实现
1 | class Test { |
异步实现
- GCD(Grand Central Dispatch)
1
2
3
4
5
6
7let queue = DispatchQueue(label: "XXX.XXX.XXX")
queue.sync {
// 同步业务逻辑
}
queue.async {
// 异步业务逻辑
} - NSOperationQueue
- NSThread
- PThread
闭包(Closure,类似匿名函数、lambda表达式)
全局函数
1 有名字但不能捕获任何值。
嵌套函数
1 有名字,也能捕获封闭函数内的值。
闭包表达式
1 无名闭包,使用轻量级语法,可以根据上下文环境捕获值。