/************************* 协议 (protocol)****************************/
// 当协议中有可选实现方法时, 该协议前要用关键字 @objc 修饰, 可选实现方法前, 用 optional 修饰
@objc protocol MarryDelegate{
func cook()
func wash()
optional func hitDouDou()
}
// 必须要实现的
protocol dividDelegate{
func lookAfterChild()
}
class Man:Person,MarryDelegate,dividDelegate {
@objc func cook() {
print("还好去了捏伊斯特学校,饭做的贼好")
}
@objc func wash() {
print("媳妇儿衣服贵, 我得用手洗")
}
// @objc func hitDouDou() {
// print("豆豆豆豆豆豆豆豆豆豆")
// }
func lookAfterChild() {
print("照顾孩纸")
}
}
// 调用协议
let man:Man = Man(name: "大锤", age: 25)
man.cook()
man.wash()
//man.hitDouDou()
/**************** Extension(扩展)*******************/
// 1. 扩展一个类遵循的协议中的方法实现
extension Man{
@objc func hitDouDou() {
print("打豆豆")
}
}
man.hitDouDou()
// 2.扩展类的方法 (给某个类添加一个方法), 类似于 OC 中的 Category类目
extension Man{
func sing(){
print("老婆,我爱你!")
}
// 扩展一个类方法
class func eat() {
print("吃饭!!!!")
}
}
man.sing()
Man.eat()
/*************** 闭包 ****************/
// 求两个整型数中的最大值
// func maxValue (a:Int,b:Int) ->Int
// 这个函数的类型是:(a:Int,b:Int) ->Int
var maxResult:((a:Int, b:Int)->Int)
// 第一种方式: 实现闭包
maxResult = {
(a:Int, b:Int)->Int in
return a>b ? a:b
}
// 第二种方式: 实现闭包
maxResult = {
a,b in
return a>b ? a:b
}
// 第三种: 实现闭包
maxResult = {
a,b in
a>b ? a:b
}
// 第四种: 实现闭包 (0代表第一位元素, 1代表第二位元素)
maxResult = {
$0>$1 ? $0:$1
}
// 第五种: 实现闭包
maxResult = {
(a,b) -> Int in
return a>b ? a:b
}
print(maxResult(a: 3, b: 5))