我们先来看一段代码
<pre>
@interface Student : NSObject
@property (nonatomic, readonly, setter=setName:) NSString *name;
@end
@implementation Student
-
(void)setName:(NSString *)name {
if (name) {
self.name = name;
}
} -
(void)cleanName {
self.name = nil;
}
@end
</pre>
非常简单的Objective-C的代码片段,当我们不期望传递参数的时候,通常会这么写:
[self setName:nil];
相比而已,Swift传递nil,语法看起来与其相似,但是它不会像Objective-C那样简单。
举个例子,简单实现一个定时器倒计时的功能:
<pre>
class ViewController: UIViewController {
@IBOutlet weak var labelForBinaryCount: UILabel!
var timer = NSTimer()
var binaryCount = 60
override func viewDidLoad() {
super.viewDidLoad()
reset(Optional.None)
}
@IBAction func start(sender: AnyObject?) {
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "countUp", userInfo: nil, repeats: true)
NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
}
@IBAction func reset(sender: AnyObject?) {
binaryCount = 60
updateText()
}
func countUp() {
binaryCount -= 1
if binaryCount == 0 {
binaryCount = 60
}
updateText()
}
func updateText() {
labelForBinaryCount.text = "\(binaryCount)s"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
</pre>
我们可以看到,reset(Optional.None),实际上传递的正是nil。
巧妙的利用了Optional的特性。
happy coding happy life.
welcom to my blog.
网友评论