Skip to content

Commit 776238a

Browse files
committed
添加protocol optional chaining
1 parent 4aa5095 commit 776238a

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

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

+18
Original file line numberDiff line numberDiff line change
@@ -631,6 +631,24 @@ class MyClass {
631631

632632
并且只有遵守了class protocol的delegate才能定义为weak这是因为在Swift中,除了class能够遵守协议,枚举和结构同样能够遵守协议而枚举和结构是值类型,不存在内存管理的问题因此只需要class类型的变量声明为weak即可
633633

634+
利用Swift的optional chaining,我们能够很方便的检查delegate是否为Nil,是否有实现某个方法:
635+
636+
以前我们要在Objective-C这样检查:
637+
638+
~~~objective-c
639+
if (self.dataSource && [self.dataSource respondsToSelector:@selector(titleForSegmentAtIndex:)]) {
640+
thisSegmentTitle = [self.dataSource titleForSegmentAtIndex:index];
641+
}
642+
~~~
643+
644+
在Swift中,非常的优雅简洁
645+
646+
~~~swift
647+
if let thisSementTitle = dataSource?.titleFroSegmentAtIndex?(index){
648+
}
649+
~~~
650+
651+
634652
新特性:
635653

636654
在Swift中,protocol变得更加强大,灵活:

0 commit comments

Comments
 (0)