gpt4 book ai didi

swift - 无法转换类型 [(key :string, value :int)] to specified type Dictionary

转载 作者:行者123 更新时间:2023-11-28 10:57:50 25 4
gpt4 key购买 nike

我有以下函数来返回排序后的字典,但我收到了这个错误:

Cannot convert value of type [(key:string,value:int)] to specified type Dictionary<String,Int>

这是我的代码:

func generatDictionaryFromString(str:String) -> Dictionary<String,Int>{
var charDict = Dictionary<String,Int>()
/* doing something here
*/
return charDict.sorted(by:<) // <-- line with the error
}

有人知道我为什么会收到此错误吗?

最佳答案

这是 Swift 类型错误

Swift返回结果类型为[(key: String, value: Int)],函数返回类型为Dictionary所以报错

所以,它被解决了

选项:1)改变函数的返回类型

func generatDictionaryFromString(str:String) -> [(key: String, value: Int)]{
let charDict = Dictionary<String,Int>()
/* doing something here
*/
return charDict.sorted(by:<)
}

选项 :2) 改变返回值。

func generatDictionaryFromString(str:String) -> (key: String, value: Int)? {
let charDict = Dictionary<String,Int>()
/* doing something here
*/
return charDict.sorted(by:<).first
}

根据您的要求,您可以更改您的实现。

关于swift - 无法转换类型 [(key :string, value :int)] to specified type Dictionary<String, Int>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42167433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com