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

swift – 使用模式匹配来过滤数组

发布时间:2020-12-14 04:57:06 所属栏目:百科 来源:网络整理
导读:这是我的代码: enum SymptomPeriod { case Day case Night}enum SymptomType { case Breathing(SymptomPeriod) case Breathlessness(SymptomPeriod) case Opression(SymptomPeriod) case Cough(SymptomPeriod) case ActivityLimited() case SecureTreatment
这是我的代码:

enum SymptomPeriod {
    case Day
    case Night
}

enum SymptomType {

    case Breathing(SymptomPeriod) 
    case Breathlessness(SymptomPeriod) 
    case Opression(SymptomPeriod) 
    case Cough(SymptomPeriod) 

    case ActivityLimited() 
    case SecureTreatment() 
}

struct Symptom {
    let type: SymptomType
    let date: NSDate
}

我有一系列的症状.

let symptomList: [Symptom] = ...

我需要使用SymptomPerion标准过滤症状列表,我尝试这样做:

let daySymtoms = symptomList.filter { (symptom) -> Bool in
    return symptom.type = ???
 }

我的问题在于过滤功能.

(我的目标是使用过滤功能而不是循环)

解决方法

一些建议

使用struct作为命名空间

您应该将您的枚举放入您的症状结构中,而不是重复症状一词(例如SymptomPeriod,SymptomType)

将SymptomType重命名为Kind

将SymptomType移动到Symptom后,可以删除名称的Symptom部分.但是,使用Type作为名称会产生冲突,因此您应该将其重命名为Kind.

将period计算属性添加到Kind

这将使过滤更容易

这是代码

struct Symptom {
    enum Period {
        case Day
        case Night
    }

    enum Kind {
        case Breathing(Period)
        case Breathlessness(Period)
        case Opression(Period)
        case Cough(Period)

        case ActivityLimited()
        case SecureTreatment()

        var period: Period? {
            switch self {
            case Breathing(let period): return period
            case Breathlessness(let period): return period
            case Opression(let period): return period
            case Cough(let period): return period
            default: return nil
            }
        }
    }

    let kind: Kind
    let date: NSDate
}

解决方案

现在过滤变得非常容易

let symptoms: [Symptom] = ...
let filtered = symptoms.filter { $0.kind.period == .Day }

(编辑:李大同)

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

    推荐文章
      热点阅读