01-closure
//: Playground - noun: a place where people can play
importUIKit
varstr ="Hello, playground"
//随机产生10个整型类型的数组
vararray: [Int] = []
for_in0..<10{
array.append(random()%20)
}
funcbiggerNumberFirst(a:Int, b:Int) ->Bool{
returna > b
}
array.sort(biggerNumberFirst)
//不需要单独声明一个函数,直接使用闭包(匿名函数)
//最完整的闭包传值
array.sort({
(a:Int, b:Int) ->Boolinreturna > b
})
//简化一:
array.sort({ (a, b)inreturna > b })
//简化二:
array.sort({ (a, b)ina > b })
//简化三(常用):编译器类型推断; $N表明传的是第N个参数(N:0,1,2....)
array.sort({ $0 > $1 })
//简化四(不推荐):
array.sort( > )
//结尾闭包: Trailing Closure
array.sort({
(a:Int, b:Int) ->Boolinreturna > b
})
//使用结尾闭包之后的调用方式:
array.sort(){a, binreturna > b}
01-protocol
//: Playground - noun: a place where people can play
importUIKit
varstr ="Hello, playground"
//结构体遵循协议
protocolFullyNamed {
//属性(get或者是get/set)+名字+类型+var
//绝对不能初始化
varfullName:String{get}
//var newFullName: String { get set }
//方法(不能有大括号)
funcrandomValue() ->Int
mutatingfuncchangeName(newName:String)
//类型方法(结构体)
staticfuncsomeTypeMethod()
}
//声明结构体,遵循FullyNamed
structPerson:FullyNamed{
// let修饰表明只读;var修改表明可读可写
varfullName:String
funcrandomValue() ->Int{
returnrandom()%10
}
mutatingfuncchangeName(newName:String) {
fullName= newName
}
staticfuncsomeTypeMethod() {
print("hello")
}
}
//实例化
varperson =Person(fullName:"Shirley")
person.changeName("Maggie")
person.fullName
//类继承协议
protocolPet {
varname:String{getset}
varbirthPlace:String{get}
funcplayWith()
//修改协议中的属性的值,不需要添加mutating关键词
funcchangeName(newName:String)
}
classDog:Pet{
varname:String="Puppy"
varbirthPlace:String="Beijing"
funcplayWith() {
print("play with me!")
}
funcchangeName(newName:String) {
name= newName
}
}
vardog =Dog()
dog.playWith()
dog.changeName("Doggy")
dog.name