Reputation:
I am want to display the three highest grades along with the names
My code:
let gradesofStudent = [
"Elias Brown": 80,
"Baris Yan": 99,
"Christian Najm": 70,
"Sam Chakra": 90,
"Alain Elliot": 55,
"Georges Obama": 77,
]
var y = " "
var name = " "
func mainFunction(stDictionary: Dictionary<String, Int>) -> ArraySlice<String>{
var emptyDic: [String: String] = [:]
for (keys, value) in gradesofStudent {
if value > 0 && value <= 59 {y = "F"}
else if value >= 60 && value <= 69 {y = "D"}
else if value >= 70 && value <= 79 {y = "C"}
else if value >= 80 && value <= 89 {y = "B"}
else {y = "A"}
emptyDic[keys] = y
}
var arrayGrades = (Array(emptyDic).sorted{$0.1 < $1.1}).map{(k,v) in return(k:v)}
var firstThree = arrayGrades[0..<3]
return(k: firstThree)
}
let v = mainFunction(stDictionary:gradesofStudent)
print (v)
I am getting the following output:
["A", "A", "B"]
What I want to get is something like [ "Baris Yan":"A", "Sam Chakra":"A", "Elias Brown":"B"]
Since i can't seem to sort the dictionary directly, I can't figure how to display the names.
Upvotes: 0
Views: 116
Reputation: 128
The below code snippet would give you the exact result you need:
let gradesofStudent = [ "Elias Brown": 80, "Baris Yan": 99, "Christian Najm": 70, "Sam Chakra": 90, "Alain Elliot": 55, "Georges Obama": 77, ]
var y = " "
var name = " "
func mainFunction(stDictionary: Dictionary)->ArraySlice<[String : String]> {
var emptyDic: [String: String] = [:]
for (keys, value) in gradesofStudent {
if value > 0 && value <= 59 {y = "F"}
else if value >= 60 && value <= 69 {y = "D"}
else if value >= 70 && value <= 79 {y = "C"}
else if value >= 80 && value <= 89 {y = "B"}
else {y = "A"}
emptyDic[keys] = y
}
var arrayGrades = emptyDic.sorted{$0.1 < $1.1}.map{(k,v) in return[k:v]}
var firstThree = arrayGrades[0..<3]
return(firstThree)
}
let v = mainFunction(stDictionary:gradesofStudent) print (v)
Upvotes: 0
Reputation: 285082
My two cents (according to the comment)
struct Student {
let name : String
let grade : Int
var letterRepresentation : String {
switch grade {
case 0..<60 : return "F"
case 60..<70 : return "D"
case 70..<80 : return "C"
case 80..<90 : return "B"
default : return "A"
}
}
}
let gradesofStudent = [Student(name: "Elias Brown", grade: 80),
Student(name: "Baris Yan", grade: 99),
Student(name: "Christian Najm", grade: 70),
Student(name: "Sam Chakra", grade: 90),
Student(name: "Alain Elliot", grade: 55),
Student(name: "Georges Obama", grade: 77)]
let threeHighestGrades = gradesofStudent.sorted(by: {$0.grade > $1.grade}).prefix(3)
print(threeHighestGrades.map({"\($0.name) - \($0.letterRepresentation)"}))
// ["Baris Yan - A", "Sam Chakra - A", "Elias Brown - B"]
Is there no letter E
?
Upvotes: 1