Example of Swift Code Using Array Map and Reduce

Feedback


Solution 1:

The function identified as

filter

can be utilized.

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

The script will evaluate every item in

dataArray

, retaining only those that match the condition where

isPurchased

is equivalent to

"false"

.


Solution 2:


The

filter

can be employed in conjunction with the

contains

function.

Model Class:

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
}


Solution 3:

Create a filtering function:

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

Implement your function with the Array filter method.

let filteredArray = dataArray.filter(notPurchased)

Frequently Asked Questions

Posted in Ios