Swift中如何参数传递空值

2016-02-17  本文已影响3279人  ba78fbce98d5

我们先来看一段代码

<pre>
@interface Student : NSObject
@property (nonatomic, readonly, setter=setName:) NSString *name;
@end

@implementation Student

@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.

上一篇 下一篇

猜你喜欢

热点阅读