使用模式匹配来过滤数组

时间:2016-06-20 22:30:44

标签: swift

这是我的代码:

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 = ???
 }

我的问题在于过滤功能。

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

2 个答案:

答案 0 :(得分:2)

一些建议

使用您的struct作为命名空间

不应重复单词Symptom(例如SymptomPeriodSymptomType),而应将您的枚举放入Symptom struct

将SymptomType重命名为Kind

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

将期间计算属性添加到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 }

答案 1 :(得分:0)

我正是这样做的:

public static string ReadSetting(string key)
    {
        System.Configuration.Configuration cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        System.Configuration.AppSettingsSection appSettings = (System.Configuration.AppSettingsSection)cfg.GetSection("appSettings");
        return appSettings.Settings[key].Value;

    }

如果您有更简单的方法,请告诉我。

相关问题