Considering these two objects :
struct Product {
let id: Int
let title: String
let price: Int
let categoryId: Int
}
struct Category {
let id: Int
let name: String
}
And these two object arrays :
let products = [
Product(id: 1, title: "snake", price: 20, categoryId: 1),
Product(id: 2, title: "soap", price: 20, categoryId: 2),
Product(id: 3, title: "cream", price: 20, categoryId: 3),
Product(id: 4, title: "dog", price: 20, categoryId: 1),
Product(id: 5, title: "car", price: 20, categoryId: 4),
]
let categorieItems = [
Category(id: 1, name: "animal"),
Category(id: 2, name: "chemichal"),
Category(id: 3, name: "food"),
Category(id: 4, name: "travel"),
]
How can I handle these two structures to assign in the cellForRowAt indexPath tableView method the product title property to cell.textLabel?.text and the corresponding category name (linked with the categoryId property) contained in categorieItems to the cell.detailTextLabel?.text
For example :
cell.textLabel?.text = snake
cell.detailTextLabel?.text = animal
You can have a function that takes category id and return category from categorieItems
like
private func getCategoryForID(_ categoryId: Int) -> Category {
categorieItems.filter { $0.id == categoryId }
}
Related
How can I see in the map of products if that product is in the favorites?
Log of products
[
{id: 1, product_name: “product one”},
{id: 2, product_name: “product two”},
{id: 3, product_name: “product three”}
]
Log of favorites
[
{id: 1, product_name: “product one”},
{id: 2, product_name: “product two”}
]
{products.map((item} =>
// Here, if the product is in the favorites list then show x else show y
// I need to check here if the product is in the favorites list, to show two different types of icons
)
I don’t know how to do, I also tried to map to favorites with product id = favorite product id, but it didn't work
var products = [{
id: 1,
product_name: 'product one'
},
{
id: 2,
product_name: 'product two'
},
{
id: 3,
product_name: 'product three'
}
]
var favorites = [{
id: 1,
product_name: 'product one'
},
{
id: 2,
product_name: 'product two'
}
]
const solution = products.map((product)=>{
return favorites.find(el=>el.product_name === product.product_name) ? 'x' : 'y'
})
I have the following tow arrays:
fetchedProducts = [
[name: "productName20", id: 20],
[name: "productName3", id: 3],
[name: "productName1", id: 1]
]
sortedProducts = [
[productName1: "1"], // I know the numbers here are string; I need them to be string
[productName20: "20"],
[productName3: "3"]
]
Now I need to sort fetchedProducts based on the order of sortedProducts so it would end up looking like the following:
fetchedProducts = [
[name: "productName1", id: 1],
[name: "productName20", id: 20],
[name: "productName3", id: 3]
]
You can try the following in Swift. Note the dictionaries in Swift are unordered so you have to use arrays for ordered collections:
let fetchedProducts = [
(name: "productName20", id: 20),
(name: "productName3", id: 3),
(name: "productName1", id: 1),
]
let sortedProducts = [
("productName1", "1"),
("productName20", "20"),
("productName3", "3"),
]
let sortedFetchedProducts = sortedProducts
.compactMap { s in
fetchedProducts.first(where: { s.1 == String($0.id) })
}
print(sortedFetchedProducts)
// [(name: "productName1", id: 1), (name: "productName20", id: 20), (name: "productName3", id: 3)]
JavaScipt realisation:
const fetchedProducts = [
{name: "productName20", id: 20},
{name: "productName3", id: 3},
{name: "productName1", id: 1}
];
const sortedProducts = [
{productName1: "1"}, // I know the numbers here are string; I need them to be string
{productName20: "20"},
{productName3: "3"}
];
const sortProducts = (fetchedProducts, sortedProducts) => {
// Extract ordered id from the sortedProducts array
const orderIds = sortedProducts.map(sorted => +Object.values(sorted));
// Find product by sorted id and put into new array
const sortedFetchedProducts = [];
orderIds.forEach(id => {
let product = fetchedProducts.find(item => item.id === id);
sortedFetchedProducts.push(product);
});
return sortedFetchedProducts;
}
const sortedFetchedProducts = sortProducts(fetchedProducts, sortedProducts);
console.log(sortedFetchedProducts);
Output:
[
{ name: 'productName1', id: 1 },
{ name: 'productName20', id: 20 },
{ name: 'productName3', id: 3 }
]
Supposing I have these two objects :
struct Product {
let id: Int
let title: String
let price: Int
let categoryId: Int
}
struct Category {
let id: Int
let name: String
}
Then I create two arrays containing those objects :
let products = [Product(id: 1, title: "snake", price: 20, categoryId: 1),
Product(id: 2, title: "soap", price: 20, categoryId: 2),
Product(id: 3, title: "cream", price: 20, categoryId: 3),
Product(id: 4, title: "dog", price: 20, categoryId: 1),
Product(id: 5, title: "car", price: 20, categoryId: 4),
]
let categorieItems = [Category(id: 1, name: "animal"),
Category(id: 2, name: "chemichal"),
Category(id: 3, name: "food"),
Category(id: 4, name: "travel"),
]
I want to create a new array which contains the names of all the product categories :
func handleCategories() -> [String] {
var categoryNames = [String]()
for product in products {
for categorieItem in categorieItems {
if product.categoryId == categorieItem.id {
categoryNames.append(category.name)
}
}
}
return categoryNames
}
This method works but I want to write one with closure (I guess map() should works)
The result should be :
categoryNames = ["animal", "chemichal", "food", "animal", "travel"]
Make a dictionary that keys the category by id, and map each product into a category by looking up its categoryId in that dict.
I used a force unwrap, assuming that products don't contain any invalid categoryIds.
struct Product {
let id: Int
let title: String
let price: Int
let categoryId: Int
}
struct Category {
let id: Int
let name: String
}
let products = [
Product(id: 1, title: "snake", price: 20, categoryId: 1),
Product(id: 2, title: "soap", price: 20, categoryId: 2),
Product(id: 3, title: "cream", price: 20, categoryId: 3),
Product(id: 4, title: "dog", price: 20, categoryId: 1),
Product(id: 5, title: "car", price: 20, categoryId: 4),
]
let categorieItems = [
Category(id: 1, name: "animal"),
Category(id: 2, name: "chemichal"),
Category(id: 3, name: "food"),
Category(id: 4, name: "travel"),
]
let categoriesById = Dictionary(uniqueKeysWithValues:
categorieItems.map { (key: $0.id, value: $0) }
)
let productCategoryNames = products.map { categoriesById[$0.categoryId]!.name }
print(productCategories)
I need to make a function that returns all parent nodes from a specific node in a tree structure.
This is an example of the structure:
struct Node
{
var name: String
var id: Int
var parentId: Int?
var children: [Node]
init(name: String, id: Int, children: [Node], parentId: Int?)
{
self.name = name
self.id = id
self.children = children
self.parentId = parentId
}
}
This would be an array of Node.
Array(
Node("A1", 1, [
Node ("A11", 11, [
Node("A111", 111, []),
Node("A112", 112, [])
]
)]),
Node("A2", 2, [
Node ("A21", 21, [
Node("A211", 211, []),
Node("A212", 212, [])
]
)]),
)
)
If I select Note "112" I should get an array like this:
[Node("A1", 1, [...]), Node ("A11", 11, [...]]
Any ideas how I can do this?
Here's a testable example:
let nodeA111 = Node(name: "A111", id: 111, children: [], parentId: 11)
let nodeA112 = Node(name: "A112", id: 112, children: [], parentId: 11)
let nodeA211 = Node(name: "A211", id: 211, children: [], parentId: 21)
let nodeA212 = Node(name: "A212", id: 212, children: [], parentId: 21)
let nodeA11 = Node(name: "A11", id: 11, children: [nodeA111, nodeA112], parentId: 1)
let nodeA21 = Node(name: "A21", id: 21, children: [nodeA211, nodeA212], parentId: 2)
let nodeA1 = Node(name: "A1", id: 1, children: [nodeA11], parentId: nil)
let nodeA2 = Node(name: "A2", id: 2, children: [nodeA21], parentId: nil)
let nodes: [Node] = [nodeA1, nodeA2]
// This is the function I want to do
func getParentNodes(forNode node: Node) -> [Node]
{
return []
}
I appreciate the help.
I have a 2D array with multiples values.
One field on this array is called group, let's imagine my array have this order:
private var myArray = [
ArrayModel(
id: 0,
name: "Test",
color: 0,
img: "img.png",
group = "myGroup"),
ArrayModel(
id: 1,
name: "Test1",
color: 0,
img: "img.png",
group: "myGroup"),
ArrayModel(
id: 2,
name: "Test2",
color = 0,
img = "img.png",
group = "myGroup3")
ArrayModel(
id: 3,
name: "Test3",
color: 0,
img: "img.png",
group: "myGroup2"),
ArrayModel(
id: 4
name: "Test4"
color: 0
img: "img.png"
group: "myGroup3")
]
Array Model
class ArrayModel: Decodable {
var id: Int
var name: String
var color: Int
var img: String
var group: String
convenience init() {
self.init()
id = 0
name = ""
color = 0
img = ""
group = ""
}
init(id: Int, name: String, color: Int, img: String, group: String) {
self.id = id
self.name = name
self.color = color
self.img = img
self.group = group
}
}
How can I move my myArray[2] to be in myArray[1] ?
My desired output is :
let myArray = [
ArrayModel(
id: 0,
name: "Test",
color: 0,
img: "img.png",
group: "myGroup")
]
[1] => same shema, but group => "myGroup"
[2] => same shema, but group => "myGroup2"
[3] => same shema, but group => "myGroup2"
[4] => same shema, but group => "myGroup3"
]
I tried this :
myArray.sorted(by: { $0.group < $1.group })
Thanks for your help!
Try this:
myArray.sort { $0.group < $1.group }
The .sort(by: ...) isn't what you need here, as you want to modify myArray (by sorting it). To do that, you have to omit the by:....
For more information, see this answer :)
This may help you to sorted by Case Sensitive but your myArray should be mutable. ex : var myArray
myArray = myArray.sorted(by: { $0.group.localizedCompare($1.group) == .orderedAscending})