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 }
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- 【翻译】动态图像监测开源代码 motion 学习-----
- vue源码学习之Object.defineProperty 对数组监听
- ruby-on-rails – 用于RSpec的未定义方法instanc
- Cocos2d-X 3.4版-怪物的AI《赵云要格斗》
- ruby-on-rails – 如何测试after_initialize回调
- c# – 我们什么时候为字典做GetHashCode()?
- swift – “在Xcode 6 Beta 4中运行应用程序时,文
- Swift学习笔记系列——(2)字符串和字符
- objective-c – UIViewController和ViewControll
- xcode – 重新加载.lldbinit而不重新加载应用程序
热点阅读
