2017-06-17 92 views
0

排序後的數組,我想用的名字斯威夫特 - 顯示與按鍵

一起顯示的三個最高等級

我的代碼:

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) 

我得到以下輸出:

[ 「A」,「A」,「B」]

我想得到的是類似於[「Baris Yan」:「A」,「Sam Chakra」:「A」,「Elias Brown」:「B 「]

由於我似乎無法直接對字典進行排序,我無法確定如何顯示名稱。

+1

如果你將'var Student:'var name:String','var Student:Int'成員,計算屬性'var letterRepresentation:String {...}'和**數組**實例。順便說一句:根據定義,字典是無序的。 – vadian

+0

斯威夫特2或3?你的代碼在Swift 3中給出了錯誤0 –

回答

2

我的兩分錢(按評論)

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

+0

愚蠢的錯字:你的'switch'會讓'A'成爲'69'和'79'。 –

+0

糟糕。非常感謝@PauloMattos – vadian

1

下面的代碼片段會給你你需要確切的結果:

讓gradesofStudent = [ 「埃利亞斯·布朗」:80, 「巴里斯嚴」:99, 「基督教Najm」:70, 「薩姆脈輪」:90, 「阿蘭埃利奧特」:55, 「喬治奧巴馬」:77, ]

VAR Y = 「」

變種名稱= 「」

FUNC mainFunction(stDictionary:詞典) - > ArraySlice < [字符串:字符串]> {

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) 打印(ⅴ)