加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

避免连续的“如果让”声明在Swift

发布时间:2020-12-14 05:53:09 所属栏目:百科 来源:网络整理
导读:参见英文答案 Using multiple let-as within a if-statement in Swift 在Swift中,我使用if声明来检查我的对象是否不为零 if let obj = optionalObj{} 但有时候,如果允许声明,我必须面对连续 if let obj = optionalObj{ if let a = obj.a { if let b = a.b
参见英文答案 > Using multiple let-as within a if-statement in Swift
在Swift中,我使用if声明来检查我的对象是否不为零
if let obj = optionalObj
{
}

但有时候,如果允许声明,我必须面对连续

if let obj = optionalObj
{
    if let a = obj.a
    {
        if let b = a.b
        {
            // do stuff
        }
    }
}

我正在寻找一种避免连续的方式,如果允许声明。

我会尝试像:

if let obj = optionalObj && if let a = obj.a && if let b = a.b
{
    // do stuff
}

但是swift编译器不允许这样做。

任何建议?

之前我写了一些关于替代品的小文章: https://gist.github.com/pyrtsa/77978129090f6114e9fb

在其他答案中还没有提到一种方法,我喜欢,是添加一堆重载的每个功能:

func every<A,B>(a: A?,b: B?) -> (A,B)? {
    switch (a,b) {
        case let (.Some(a),.Some(b)): return .Some((a,b))
        default:                       return .None
    }
}

func every<A,B,C>(a: A?,b: B?,c: C?) -> (A,C)? {
    switch (a,b,c) {
        case let (.Some(a),.Some(b),.Some(c)): return .Some((a,c))
        default:                                 return .None
    }
}

// and so on...

这些可以用于if语句,case表达式以及optional.map(…)链:

// 1.
var foo: Foo?
if let (name,phone) = every(parsedName,parsedPhone) {
    foo = ...
}

// 2.
switch every(parsedName,parsedPhone) {
    case let (name,phone): foo = ...
    default: foo = nil
}

// 3.
foo = every(parsedName,parsedPhone).map{name,phone in ...}

必须为每个添加重载是模板,但只能在库中完成一次。类似地,通过使用Functor方法(即使用< ^&&>运算符),您需要以某种方式创建curried函数,这也导致一些样板。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读