-4

I have an array of struct, the struct contains 5 elements, I want to get all values in the array where one element is equal to a certain value

Then I have an array of the above struct like so,

I want to print all elements in parr where parr.station equal to certain value

struct allproducts {
    let sendtime : String
    let max_value : String
    let station : String
    let product : String
    let availability : String
}

var parr = [allproducts]()
0

3 Answers 3

0

Assuming that parr is already contains objects, you could simply achieve it by using filter method:

let filtered = parr.filter { $0.station == "your value" }

Obviously, you would change "your value" to your desired value.

Sidebar note: Naming the struct should follow the upper camel case convention. You should call it: AllProducts or more logically Product.

Sign up to request clarification or add additional context in comments.

1 Comment

am new to swift ,thank you
0
let arryoucertainValue = parr.filter {$0.max_value <= 10}

use the filter function to get values from the array based on some conditions for eg here I have fetched all element of the array which contains max_value property <= 10

Comments

0
// declaring the model in the appropiate file
struct Product {
    let sendtime : String
    let max_value : String
    let station : String
    let product : String
    let availability : String
}


//instantiating the products
let prod1 = Product(station : "a", ....)
let prod2 = Product(station : "b", ...)
let prod3 = Product(station : "c", ...)




//adding the products to a collection
let allProducts= [prod1 , prod2 , prod3 ]

//filter all products based on a condition
let filteredArray = allProducts.filter { $0.station == "a") }

print(filteredArray)

I would recommend you to read a good book about introduction to OOP.

4 Comments

"I would recommend you to read a good book about introduction to OOP" if I'm not mistaking, such a task has nothing to do with knowing OOP :)
It has a bit Ahmad. Is not in the actual question about the filter function but in the naming of the struct. You cannot name a model AllProducts... you should be able to see that. PS: It is if I am not mistaken not "If I'm not mistaking"
Well, if you are meant by mentioning this the naming convention, I would say good point. But not the filtering...
That's what I meant indeed. You're right, the filtering function has nothing to do with OOP.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.