我的函数关闭存在问题。我尝试从UserDefault排序数组。当我尝试使用“ let topScoreSorted = userDefaultsArray.sorted {$ 0.1 <$ 1.1}”时,构建失败,并显示错误“无法在当前上下文中推断闭包类型”。我该如何解决?
func addScoreToUserDefault(with key: String, and value: Int) {
// UserDefaults array
var userDefaultsArray = defaults.dictionary(forKey: "TopScore")!
let topScoreSorted = userDefaultsArray.sorted { $0.1 < $1.1 }
// checks if name exists in userDefault array and if value is higher than in origin
for n in 0...3 {
if topScoreSorted[n].key == key && topScoreSorted[n].value <= value {
userDefaultsArray.removeValue(forKey: topScoreSorted[n].key)
userDefaultsArray[key] = value
}
}
// check if array has more than 5 elements and if value is higher than origin, if true removes last value and add higher one
if topScoreSorted.count >= 5 && topScoreSorted[0].value <= value {
userDefaultsArray.removeValue(forKey: topScoreSorted[0].key)
userDefaultsArray[key] = value
} else if topScoreSorted.count < 5 {
userDefaultsArray[key] = value
}
let sortedArray = userDefaultsArray.sorted { $0.1 < $1.1 }
defaults.set(userDefaultsArray, forKey: "TopScore")
}
答案 0 :(得分:1)
userDefaultsArray
是[String:Any]
类型,当您比较$0.1 < $1.1
时,谁知道values
是什么类型?
您正在尝试比较Any
类型的值,可以是任何值。它可以是String
或Int
,也可以是Double
。
使用Any
时,您需要将变量类型转换为特定类型,或者在开始本身中指定Dictionary
类型。
示例1 :对value
let topScoreSorted = userDefaultsArray.sorted {
if let value1 = $0.1 as? Int, let value2 = $1.1 as? Int {
return value1 < value2
}
return false
}
示例2 :指定Dictionary
类型
var userDefaultsArray = UserDefaults.standard.dictionary(forKey: "TopScore") as! [String:Int]
let topScoreSorted = userDefaultsArray.sorted { $0.1 < $1.1 }