let/var
数组
//完整版
//let定义的数组,内容不可变
let arr: Array<Int> = Array<Int>()
let arr = Array<Int>()
let arr = [Int]()
let arr = [1, 2, 3]
//根据位置进行操作,元素按顺序排列
arr[1]
字典
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"]
循环
//范围
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
条件判断
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
switch
var i = 1
switch i {
case 0..<10:
print("xxx")
fallthrough
case 1:
print("yyy")
default:
print("zzz")
}
enum
enum Weekday {
case Monday
case Thuesday
}
var w: Weekday = Weekday.Monday
w = .Thuesday
Optional
var i: Int? //必须使用!手动拆包
i = 123
var j = i! + 123
var k: Int! //自动拆包
k = 34
var m = k + 34
struct
struct Student {
var name: String
var age: Int
}
//值类型
var st01 = Student(name: "Lisi", age: 23)
var st02 = st01 //复制,变成两个
st01.name = "Zhangsan"
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()
protocol
//约定一个类型必须要具备某种功能
//约束
//可以有方法、计算属性
//不能有存储属性、不能实现方法
protocol BiteProtocol {
var a: Int { get set }
var b: Int { get }
func bite()
}
class Tiger : BiteProtocol {}
var bp: BiteProtocol = Tiger()
extension
//1. 将类拆分成多个部分
//2. 给已有类型增加新功能
运算符重载
func +(lhs: Tiger, rhs: Tiger) -> Tiger {
return ....
}
闭包
//封装一段可执行代码
//匿名函数
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)
lazy
//第一次使用时才加载
泛型(Generics)
元组
let a = (1, 3)
a.0
let b = (first: 23, second: 45)
b.first
Any/AnyObject
inout
defer
final
public/internal/private
@autoclosure