Android编程中接口和抽象类的使用实际上是很是频繁的,刚开始接触Swift的时候,发现Swift里面没有抽象类这个概念,很是别扭,其实Protocol就是相似Java中的接口和抽象类的东西。接下来咱们看看如何在Swift中实现一个抽象类。
学过Java的都知道,抽象类具备如下特性:程序员
Protocol最经常使用的方法是相似Java中的Interface,用来声明一些子类必须实现的属性和方法。
因此抽象方法就不须要咱们去思考了,很是简单,直接在Protocol中声明便可编程
protocol AbstractClass { var value : String{get set} func abstractFun() }
这个任务看上去很是简单,随便百度一下就知道,如何给Protocol扩展方法。swift
extension AbstractProtocol{ func extensionFun() { print("this is a extensionFun") } }
确实很是简单,不过抽象类中的实体方法是能够修改抽象方法中的参数的,可是上述代码中,若是直接给抽象类中的属性赋值,编译器会报错Cannot assign to property: 'self' is immutable
不过这个错误很好解决,直接给方法前面加上一个mutating
就能够了。
虽然这种方法可以直接编译经过,不过你会发现,当咱们的类实现Protocol的时候,咱们并不能调用到extensionFun
方法,依然会报Cannot assign to property: 'self' is immutable
错误,也就是说,必需要mutable
的方法才能调用被mutating
修饰的方法。
在子类中没法使用父类中的方法,这显然和Java中的抽象类不符,因此咱们须要换一种方法来实现实体方法
到底该如何作呢,其实只须要在Protocol后面加上 : class
就能够了,这是用来限定协议只能应用在class上面,加上这个参数以后,咱们就能够在扩展出来的方法中为抽象属性赋值了。segmentfault
protocol AbstractClass : class{}
为Protocol实现实体属性,这个比较简单,和为已有类扩展属性是同样的,能够参考个人文章Swift快速为类扩展属性,就能够很是轻松的声明一个实体属性。学习
var noNeedImplementProperty : String{ get{ return get0() } set{ set0(newValue)} }
最后咱们来看一个简单的抽象类的完整代码this
protocol AbstractProtocol : class , Property{ var mustImplementProperty : String{get set} func mustImplementFun() } extension AbstractProtocol{ var noNeedImplementProperty : String{ get{ return get0() } set{ set0(newValue)} } func noNeedImplementFunction() { print("this is a noNeedImplementFunction") self.noNeedImplementProperty = "[set in noNeedImplementFunction]" print("I can use noNeedImplementProperty,this property value is : \(self.noNeedImplementProperty)") self.mustImplementProperty = "[set in noNeedImplementFunction]" print("I can use mustImplementProperty,this property value is : \(self.noNeedImplementProperty)") } } class Test: AbstractProtocol { var mustImplementProperty: String = "" func mustImplementFun() { print("this is a mustImplementFun") self.noNeedImplementProperty = "[set in mustImplementFun]" print("I can use noNeedImplementProperty,this property value is : \(self.noNeedImplementProperty)") self.mustImplementProperty = "[set in mustImplementFun]" print("I can use mustImplementProperty,this property value is : \(self.noNeedImplementProperty)") } }
Android程序员在学习IOS的过程当中,确定会有不少思想禁锢,有不少Android里面有的东西IOS里面是没有的,不过咱们能够尽可能想办法去实现。其实,最好的办法是去接受IOS里面的一些思想,多看别人写的代码,可以获得一些启发。code