由于闭包类型,构建失败

Build fails because of closure type

我的函数中有闭包问题。我尝试从 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 { [=10=].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 { [=10=].1 < .1 }

    defaults.set(userDefaultsArray, forKey: "TopScore")
}

userDefaultsArray[String:Any] 类型,当您比较 [=14=].1 < .1 谁知道 values 是什么类型?

您正在尝试比较 Any 类型的值,可以是任何值。它可以是 StringInt 也可以是 Double.

使用 Any 时,您需要将变量类型转换为特定类型或在开始时指定 Dictionary 类型。

示例 1:类型转换 value

let topScoreSorted = userDefaultsArray.sorted {
    if let value1 = [=10=].1 as? Int, let value2 = .1 as? Int {
        return value1 < value2
    }
    return false
}

示例 2:指定 Dictionary 类型

var userDefaultsArray = UserDefaults.standard.dictionary(forKey: "TopScore") as! [String:Int]
let topScoreSorted = userDefaultsArray.sorted { [=11=].1 < .1 }