Skip to content

Commit 4aa5095

Browse files
committed
添加protocol语法
1 parent c7c5687 commit 4aa5095

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

Swift学习:Swift与Objective-C/Swift学习:Swift与Objective-C.md

+56
Original file line numberDiff line numberDiff line change
@@ -580,10 +580,66 @@ Swift的初始化方法让我们只关注对象的初始化。之前在OC世界
580580

581581
语法:
582582

583+
在Objective-C中我们这么声明Protocol:
584+
585+
~~~objective-c
586+
@protocol SampleProtocol <NSObject>
587+
- (void)someMethod;
588+
@end
589+
~~~
590+
591+
而在Swift中:
592+
583593
~~~swift
594+
protocol SampleProtocol
595+
{
596+
func someMethod()
597+
}
598+
~~~
584599

600+
在Swift遵循协议:
601+
602+
~~~swift
603+
class AnotherClass: SomeSuperClass, SampleProtocol
604+
{
605+
func someMethod() {}
606+
}
585607
~~~
586608

609+
那么之前Objective-C的protocol中,我们可以标志optional那在Swift中呢?
610+
611+
遗憾的是,目前纯Swift的protocol还不支持optional但根据苹果官方论坛的一位员工的回答,未来Swift是会支持的
612+
613+
> Optional methods in protocols are limited to @objc protocols only because we haven't implemented them in native protocols yet. This is something we plan to support. We've gotten a number of requests for abstract/pure virtual classes and methods too.
614+
615+
>— Joe Groff
616+
>
617+
> Source: https://devforums.apple.com/message/1051431#1051431
618+
619+
`protocol`和`delegate`是紧密联系的那么我们在Swift中如何定义Delegate呢?
620+
621+
~~~swift
622+
protocol MyDelegate : class {
623+
}
624+
625+
class MyClass {
626+
weak var delegate : MyDelegate?
627+
}
628+
~~~
629+
630+
注意到上面的protocol定义后面跟着的class这意味着该protocol只能被class类型所遵守
631+
632+
并且只有遵守了class protocol的delegate才能定义为weak这是因为在Swift中,除了class能够遵守协议,枚举和结构同样能够遵守协议而枚举和结构是值类型,不存在内存管理的问题因此只需要class类型的变量声明为weak即可
633+
634+
新特性:
635+
636+
在Swift中,protocol变得更加强大,灵活:
637+
638+
1. `class`,`enum`,`structure`都可以遵守协议
639+
640+
641+
642+
587643

588644
--
589645
参考:

0 commit comments

Comments
 (0)