如何将iOS代码写的更“Swift”一点

这篇文章记录要将代码写的更像“Swift”的知识点

oc中的协议(protocol)里的函数是有 @optional 和 @required 属性的。但是 Swift 中协议的方法是必须要实现的。有两种方法,一种是把协议转化为 objective-c 的方式,一种是用扩展(extension)。
第一种:

@objc protocol SomeProtocol{
	func requiredFunc()
	@objc optional func optionalFunc()
}

第二种(我觉得这种更“Swift”一点):

protocol SomeProtocol{
	func requiredFunc()
	func optionalFunc()
}
extension SomeProtocol{
	func optionalFunc(){
		print("Dumb Implementation")
	}
}
Class SomeClass: SomeProtocol{
	func requiredFunc(){
		print("Only need to implement the required")
	}
}

将 oc 的动态性写的 “Swift”一点。

if([someImage respondsToSelector:@selector(shake)]){
  [someImage performSelector:shake];
}

Swift 中可以这样写,用 protocol 来处理:

if let shakeableImage = someImage as? Shakeable{
  shakeableImage.shake()
}

oc 中的类包含一个代理属性

@protocol SomeProtocolDelegate <NSObject>
	-(void)doSmething;
@end
@interface ViewController
	@property(nonatomic,weak) id<SomeProtocolDelegate> delegate;
@end

如果用swift 实现

@objc protocol SomeProtocolDelegate {
    func doSmething()
}

public class ViewController: UIViewController {
    weak var delegate: SomeProtocolDelegate?
}

或者(我觉得这种更“Swift”一点)

protocol SomeProtocolDelegate : class{
    func doSmething()
}

public class ViewController: UIViewController {
    weak var delegate: SomeProtocolDelegate?
}

上面三个知识点综合起来运用就是:
oc代码

//.h
//定义方法列表
@protocol SomeProtocolDelegate <NSObject>
@required //强制方法列表
-(void)doSmething;
@optional //可选方法列表
-(void)optionalFunc;
@end

//定义公开属性
@interface ViewController
//实现了SomeProtocolDelegate协议的对象才能有资格成为delegate
@property(nonatomic,weak) id<SomeProtocolDelegate> delegate;
@end

//.m
//在适当的地方调用被代理对象的方法
...
//绑定了doSmething方法的对象,才向它发送消息(即调用方法).
if ([self.delegate respondsToSelector:@selector(doSmething)]) {
    [self.delegate performSelector:@selector(doSmething)];
}

Swift 代码

protocol SomeProtocol: class{
	func requiredFunc()
	func optionalFunc()
}
extension SomeProtocol{
	func optionalFunc(){
		print("Dumb Implementation")
	}
}
class ViewController: UIViewController {
    weak var delegate: SomeProtocolDelegate?
}


//.m
//在适当的地方调用被代理对象的方法
if let vc = mVC as? SomeProtocolDelegate{
  vc.optionalFunc()
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值