rayjuneWu

To be a better man.

嗨,我是吴蕾君 (@rayjuneWu),一名来自中国杭州的 iOS Developer / PM。


Swift2-同时解包多个可选值(Optionals)

话不多说,直接上代码

方式1:

1
2
3
4
5
6
var optional1: String?
var optianal2: String?

if let optional1 = optional1, optianal2 = optianal2 {
    
}

看起来很美~问题来了:如果我希望处理optional1有值,optional2没值的情况怎么办?聪明的你立马想到了:

1
2
3
4
5
6
if let optional1 = optional1 {
    guard let _ = optianal2 else{
        print(optional1)
        return
    }
}

那optional1无值,optional2有值的情况,optional1与optional2都没值的情况呐…别打我:)
可见,方法一在遇到需要对多个可选值分开判断有无值的时候,似乎变得十分无力。可见的一个实际应用场景是登录界面:假设我们有loginNameTextFieldpasswordTextField两个输入框,当用户点击登录按钮时,我们需要对两个输入框进行是否有值的判断,进而给用户抛出对应的错误。
那有没有其他的方式来解包多个可选值?我们来看看第二种方式看是否可以优雅地解决这个问题。

方式2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//Swift2
var username: String?
var password: String?

switch (username, password) {
case let (username?, password?):
print("Success!")
case let (username?, nil):
print("Password is needed!")
case let (nil, password?):
print("Username is needed!")
case (nil, nil):
print("Password and username are needed!")
}

看起来好多了~等等,case let (username?, nil):中的?是什么鬼,无需惊恐,这里的?跟可选值的?没有一点关系。username?表示的是username有值, nil即表示无值。事实上,这个?Swift2新增的语法,我们来看看Swift2以前是怎样的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//Before Swift2
var username: String?
var password: String?

switch (username, password) {
case let (.Some(username), .Some(password)):
print("Success!")
case let (.Some(username), .None):
print("Password is needed!")
case let (.None, .Some(password)):
print("Username is needed!")
case (.None, .None):
print("Password and username are needed!")
}

相比较而言,新的语法看起来精简了许多。

最近的文章

Swift:Map,FlatMap,Filter,Reduce指南

此文初始发布在我的简书。 Swift是支持一门函数式编程的语言,拥有Map,FlatMap,Filter,Reduce针对集合类型的操作。在使用Objective-C开发时,如果你没接触过函数式编程,那你可能没听说过这些名词,希望此篇文章可以帮助你了解Swift中的Map,FlatMap,Filte …

于  Swift 继续阅读
更早的文章

在Swift中使用Storyboard和Segue时的依赖注入

Demo下载我们都知道在使用Storyboard时,实现依赖注入总是有点不优雅,让我们先来看看在Objective-C时如何使用: Objective-C123456789101112131415161718//In RJDemoViewController.m- (void)setDependen …

于  Swift 继续阅读
comments powered by Disqus