如何根据某些条件在swift中减少数组

时间:2017-02-17 07:49:47

标签: ios arrays swift

我需要在Swift中了解一个很好的解决方案,以解决我面临的以下问题。

我有一个声明为var dataArray = [PlanModel]()的模型数组。

class PlanModel: {

var isPurchased:String?
var planName:String?
}

现在我从服务器获取数据,然后用模型填充dataArraydataArray由3个模型组成。模型的价值是:

模型1:

isPurchased = "true"
planName = "Question"

模型2:

isPurchased = "true"
planName = "Personal"

模型3:

isPurchased = "false"
planName = "Full"

我需要的是通过检查isPurchased的值来检查是否购买了计划来减少此阵列。如果它是真的从数组中删除它,如果它是假的,那么将它保留在数组中。

请告诉我在Swift中执行此操作的简单有效方法是什么?

5 个答案:

答案 0 :(得分:6)

您可以使用filter功能

var reducedArray = dataArray.filter {$0.isPurchased == "false"}

这会检查dataArray的每个元素,如果元素isPurchased"false",它会保留它

答案 1 :(得分:3)

您可以将filtercontains功能

一起使用

模特课程:

class PlanModel {

    var isPurchased:String?
    var planName:String?

    init(isPurchased:String?, planname:String?) {
        self.isPurchased = isPurchased
        self.planName = planname
    }
}

override func viewDidLoad() {
        super.viewDidLoad()

        var plan = [PlanModel]()            
        plan.append(PlanModel(isPurchased: "true", planname: "Question"))
        plan.append(PlanModel(isPurchased: "true", planname: "Personal"))
        plan.append(PlanModel(isPurchased: "false", planname: "Full"))

        // Filter function
        plan = plan.filter {
            ($0.isPurchased?.contains("false"))!
        }
        print(plan.count)
        // 1
}

答案 2 :(得分:1)

创建过滤功能:

func notPurchased(planModel: PlanModel) -> Bool{
   return planModel.isPurchased == "false"
}

并使用传入函数的Array过滤函数

let filteredArray = dataArray.filter(notPurchased)

答案 3 :(得分:0)

因为如果符合某些条件,您正在寻找从数组中删除该项目,您可以执行以下代码:

dataArray = dataArray.filter({ $0.isPurchased == "False"})

我发现这是最好的方法之一,我使用的是Swift 3

现在在旁注中,我建议使用structs而不是模型类

答案 4 :(得分:0)

在发布我的解决方案之后,让我告诉你,更好的改变是从String到Bool的购买类型。

现在......

class PlanModel 
{

    var isPurchased:String?
    var planName:String?
}

let p1: PlanModel = PlanModel()
p1.isPurchased = "true"
p1.planName = "Question"

let p2: PlanModel = PlanModel()
p2.isPurchased = "true"
p2.planName = "Personal"

let p3: PlanModel = PlanModel()
p3.isPurchased = "false"
p3.planName = "Full"

var plans: [PlanModel] = [ p1, p2, p3 ]

// Filter elements with `isPurchased` property
// set to `true`. As isPurchased is marked as an
// `Optional` type I check that it's not nil before
// process it
plans = plans.filter()
{ 
    guard let isPurchased = $0.isPurchased else 
    { 
        return false 
    } 

    return isPurchased == "true" 
}


plans.forEach()
{ 
    if let planName = $0.planName
    {
        print(planName)
    }
    else
    {
        print("unnamed")
    }
}