-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortByPrice.swift
More file actions
43 lines (38 loc) · 879 Bytes
/
SortByPrice.swift
File metadata and controls
43 lines (38 loc) · 879 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
//
// SortByPrice.swift
// functional-programming
//
// Created by Oktavia Citra on 20/08/22.
//
import Foundation
// MARK: - Model
struct Product {
let name: String
let category: Category
let price: Float
enum Category {
case clothes
case shoes
case bags
}
}
// MARK: - Before
func sortByPrice(in products: [Product]) -> [Product] {
var result = products
for i in 0..<result.count - 1 {
var min_index = i
for j in i..<result.count {
if result[i].price < result[min_index].price {
min_index = j
}
}
let temp = products[i]
result[i] = result[min_index]
result[min_index] = temp
}
return result
}
// MARK: - After
func sortByPrice(in products: [Product]) -> [Product] {
products.sorted(by: { $0.price < $1.price })
}