Swift中的Protocol你知道多少呢?

什么是Protocol?

protocol是swift中的一种自定义约束,一般用于定义某些类的一种共同特性

定义一个protocol

protocol Student {

    func getName()

    func getGrade()

}

某个class、struct、enum遵守这个约定,需要实现约定的方法(注意:如果里面的方法有参数,不能有默认值)

struct Person:Student {

    func getName() {

        print("my name")

    }   

    func getGrade() {

        print("my grade")

    }    

}

 protocol中也可以定义属性,定义的属性必须制定该属性支持的操作(get、set)

protocol PersonProtocol{

    var height:Int{get set}

    func getName()

    func getSex()

    func getgrade(name:String)

    func getAge(age:Int)

   // func getAge(age:Int = 0)  ❌ Default argument not permitted in a protocol method

}

height在protocol中是一个computed property,但在遵守该约定的类型中可以简单的定义成一个stored property
当protocol中定义了一个只读属性,其实我们也可以在遵守该约定的类型中完成该属性的可读可写

protocol PersonProtocol{

    var height:Int{get set}

    var weight:Int{get}

    func getName()

    func getSex()

    func getgrade(name:String)

    func getAge(age:Int)

}

struct Person:PersonProtocol {

    var height: Int = 178

    var weight: Int = 120

    func getName() {

        print("my name")

    }

    func getSex() {

        print("my sex")

    }

    func getgrade(name: String) {

        print("my grade")

    }

    func getAge(age: Int) {

        print("my age")

    }

}

var person1 = Person()

person1.height   // 178

person1.height = 189

person1.height    // 189


person1.weight    // 120

person1.weight = 160

// 当我们把person从Person转换成PersonProtocol时 他就是只读的了

(person1 as PersonProtocol).weight = 160 //cannot assign to property: 'weight' is a get-only property




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值