Swift - 使用键显示已排序的数组

时间:2017-06-17 20:50:39

标签: swift sorting

我想显示三个最高等级以及名称

我的代码:

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)

我得到以下输出:

[&#34; A&#34;,&#34; A&#34;,&#34; B&#34;]

我想要的是[&#34; Baris Yan&#34;:&#34; A&#34;,&#34; Sam Chakra&#34;:&#34; A&#34;, &#34; Elias Brown&#34;:&#34; B&#34;]

由于我似乎无法直接对字典进行排序,因此我无法确定如何显示字典。

2 个答案:

答案 0 :(得分:1)

我的两分钱(根据评论)

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"]

没有字母E吗?

答案 1 :(得分:0)

以下代码段会为您提供所需的确切结果:

让gradeofStudent = [     “伊莱亚斯布朗”:80,     “Baris Yan”:99,     “Christian Najm”:70岁,     “Sam Chakra”:90,     “Alain Elliot”:55岁,     “乔治奥巴马”:77, ]

var y =“”

var name =“”

func mainFunction(stDictionary:Dictionary) - &gt; ArraySlice&lt; [String:String]&gt; {

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)

}

让v = mainFunction(stDictionary:gradesofStudent) print(v)